我是python新手。我想把一个指向结构的指针从我的C代码发送到一个Python函数,然后从Python内部访问C结构。在
我的结构有两个数据成员。是的
int num_of_ker;
char *ker_name[50];
我是怎么从here得到答案的。在
我的项目。我
^{pr2}$在主.cpp在
#include <stdio.h>
#include <Python.h>
extern "C" // only needed when compiling in C++
{
#include "MyProject_wrap.c"
}
// struct SPythoned is defined within MyProject_wrap.c just included above
void PythonTest(void)
{
Py_Initialize(); // Init Python
SWIG_init(); // Initialise SWIG types
init_MyProject(); // Init our project wrapped by Swig
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"./\")");
SPythoned Object;
PyObject *pMod, *pGlobalDict, *pFunc, *pResult, *pArg;
Object.num_of_ker = 2;
int i;
for(i=0;i<2;i++)
{
char name[50];
sprintf(name,"kernel_%d",i);
Object.ker_name[i]=strdup(name);
}
pMod = PyImport_ImportModule("PyTest"); // Load "PyTest.py" (it will create a compiled version "PyTest.pyc")
if (pMod)
{
pGlobalDict = PyModule_GetDict(pMod); // Get main dictionary
if (pGlobalDict)
{
pFunc = PyDict_GetItemString(pGlobalDict, "TestObject"); // Look for function TestObject
if (pFunc)
{
pArg = SWIG_NewPointerObj((void*)&Object, SWIGTYPE_p_SPythoned, 1); // Get Python Object for our Structure Pointer
if (pArg)
{
pResult = PyObject_CallFunction(pFunc, "O", pArg);
Py_CLEAR(pResult);
}
}
}
}
Py_Finalize();
}
int main()
{
PythonTest();
return 0;
}
在PyTest.py在
import MyProject
def TestObject(o):
print "ker_num " , o.num_of_ker
for i in range(o.num_of_ker):
print "kername ",o.ker_name[i]
在main.cpp
中,我正在初始化num_of_ker
和{PyTest.py
文件访问num_of_ker
变量,但我不知道如何访问PyTest.py
文件中的ker_name
。有人能帮我吗?在
目前没有回答
相关问题 更多 >
编程相关推荐