void printDict(PyObject* obj) {
if (!PyDict_Check(obj))
return;
PyObject *k, *keys;
keys = PyDict_Keys(obj);
for (int i = 0; i < PyList_GET_SIZE(keys); i++)
{
k = PyList_GET_ITEM(keys, i);
char* c_name = PyString_AsString(k);
printf("%s\n", c_name);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Py_Initialize();
if (!Py_IsInitialized())
{
system("PAUSE");
return -1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyRun_SimpleString("sys.path.append('E:\TestCase\vs2013 + python\TestPython\')");
PyObject* pModule = PyImport_ImportModule("CCallPython");
if (!pModule)
{
printf("Cant open python file!\n");
getchar();
return -1;
}
//模块的字典列表
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary.\n");
getchar();
return -1;
}
printDict(pDict);
printf("\n\n");
// 全局函数调用,带参数,带返回值
PyObject* pFunParam = PyDict_GetItemString(pDict, "CFunParam");
PyObject* param_tuple = PyTuple_New(2);
PyTuple_SetItem(param_tuple, 0, Py_BuildValue("i", 2));
PyTuple_SetItem(param_tuple, 1, Py_BuildValue("s", "hello, word"));
PyObject* pRet2 = PyObject_CallObject(pFunParam, param_tuple);
int iret = 0;
PyArg_Parse(pRet2, "i", &iret);
// 全局函数调用,python内部的对象作为参数
PyObject* pFunPythonParam = PyDict_GetItemString(pDict, "CFunPythonParam");
PyObject* python_class_param = PyDict_GetItemString(pDict, "PythonClass");
PyObject* p1 = PyInstance_New(python_class_param, NULL, NULL);
PyObject* param_python = PyTuple_New(1);
PyTuple_SetItem(param_python, 0, Py_BuildValue("O", p1));
PyObject* pRet3 = PyObject_CallObject(pFunPythonParam, param_python);
// 类调用
PyObject* pClass = PyDict_GetItemString(pDict, "CInterfaceForC");
PyObject* p2 = PyInstance_New(pClass, NULL, NULL);
PyObject* pclassinvoke1 = PyObject_CallMethod(p2, "geti", NULL);
PyObject* pclassinvoke2 = PyObject_CallMethod(p2, "seti", "i", 5);
getchar();
return 0;
}
CCallPython.py---
def CFun():
print "i am come from python"
def CFunParam(x, y):
z = x * x
print z
print y
return z
class PythonClass():
def __init__(self):
self.i = 0
self.j = 0
def mem_fun(self):
self.i = 10
self.j = 20
print "error"
def CFunPythonParam(x):
print "i am a function, the param is python class"
x.mem_fun()
print x.i
print x.j
return 1
class CInterfaceForC:
def __init__(self):
self.i = 0
self.j = 1
def geti(self):
print "geti"
return self.i
def seti(self, iIn):
self.i = iIn
print "seti, the i is "
print self.i
def setj(self, jIn):
self.j = jIn
classfun = CInterfaceForC()
classfun.seti(100)
print classfun.geti()
print "success"
b1 = PythonClass()
#CFunPythonParam(b1)