- 论坛徽章:
- 0
|
在C++为主的程序框架中调用python函数失败,不知道是什么原因
但是我在做计算的时候要调用numpy,同样一个sin函数
print("math.sin = %f" % math.sin(3.14))
print("numpy.sin = %f" % numpy.sin(3.14))
第二句死活异常,报的错是类型异常,
主要是第三方库的问题,但没有找到解决问题的办法。不知道如何搞,大家帮忙
如果调用的是函数中调用的都是标准库模块的好像没有什么问题。
下面是代码:
/////////////////////////////////////////////////////////////////////////////////////
python代码(python2.72)
hellomod.py
# -*- coding: utf-8 -*-
import os
import string
import math
import numpy
def c2python(name):
print("python out,hello %s" %name)
def python2c(a,b):
r1=a+b
r2 = os.getcwd()
return (r1,r2)
def mypdf0(a):
print(string.upper(a))
print("math.sin = %f" % math.sin(3.14))
print("numpy.sin = %f" % numpy.sin(3.14))
return math.sin(3.14)
if __name__ == "__main__":
mypdf0(3.14)
/////////////////////////////////////////////////////////////////////////////////////
C代码(vc6)
#include "StdAfx.h"
#include "wtypes.h"
#include "winbase.h"
#include "cstdio"
#include "cstdlib"
#include "stdafx.h"
#include "iostream"
#include "algorithm"
#include "Python.h"
int main(int argc, char* argv[])
{
char format[1024];
char path[256];
using namespace std;
int result = -1;
Py_Initialize();
if (!Py_IsInitialized())
return -1;
result = PyRun_SimpleStringFlags("import sys",NULL);
::GetCurrentDirectory(256,(LPTSTR)path);
sprintf(format,"sys.path.append('%s')",path);
result = PyRun_SimpleStringFlags(format,NULL);
result = PyRun_SimpleStringFlags("sys.path.append('./')",NULL);
PyObject* pModule = PyImport_ImportModule("hellomod");
if (!pModule)
{
cout<<"导入模块失败!\n"<<endl;
return -1;
}
PyObject* pFunHi = PyObject_GetAttrString(pModule, "mypdf0");
if (!pFunHi || !PyCallable_Check(pFunHi))
{//检查函数是否可以被调用
cout<<"函数mypdf0未找到!\n"<<endl;
return -1;
}
PyObject* pargs = PyTuple_New(1);//多个就构造多个
PyTuple_SetItem(pargs, 0, Py_BuildValue("s","abc"));
PyObject* okfun = PyObject_CallObject(pFunHi, pargs);
if (!okfun)
{
char* error = PyString_AsString(PyObject_Str(PyErr_Occurred()));
cout << error << endl;
}
Py_DECREF(pFunHi);
Py_DECREF(pargs);
Py_DECREF(pModule);
Py_Finalize();
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////
|
|