将C结构传递给python函数并访问python中的char 2d数组,该数组在C中初始化

时间:2015-02-12 12:04:35

标签: python c++ c swig

我是python的新手。我想从C代码向Python函数发送一个指向结构的指针,然后从Python中访问C结构。

我的结构有两个数据成员。他们是

int num_of_ker;
char *ker_name[50];

我从here获得了解决方案。

MyProject.i

%module MyProject   
%inline %{       
struct SPythoned 
{
        int num_of_ker;
        char *ker_name[50];
};
%}

的main.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_kerker_name数据成员。我可以从num_of_ker文件访问PyTest.py变量,但我无法获取ker_name文件中PyTest.py的访问权限。任何人都可以帮助我吗?

0 个答案:

没有答案