2014-10-31 86 views
1

我的C++程序:我如何从python获得C++结构?

#include <iostream> 

using namespace std; 

struct FirstStructure 
{ 
public: 
    int first_int; 
    int second_int; 
}; 

struct SecondStructure 
{ 
public: 
    int third_int; 
    FirstStructure ft; 
}; 

int test_structure(SecondStructure ss) 
{ 
    int sum = ss.ft.first_int + ss.ft.second_int + ss.third_int; 
    return sum; 
} 

extern "C" 
{ 
    int test(SecondStructure ss) 
    { 
     return test_structure(ss); 
    } 
} 

我编译cpp文件使用此命令的 “g ++ -shared -fPIC -o array.so array.cpp”。 然后我调用该文件array.so使用Python,我的Python程序,因为这些:

#coding=utf-8 

import ctypes 
from ctypes import * 


class FirstStructure(Structure): 
    _fields_ = [ 
     ("first_int", c_int), 
     ("second_int", c_int) 
    ] 


class SecondStructure(Structure): 
    _fields_ = [ 
     ("third_int", c_int), 
     ("ft", FirstStructure) 
    ] 


if __name__ == '__main__': 
    fs = FirstStructure(1, 2) 
    ss = SecondStructure(3, fs) 
    print ss.ft.first_int 
    lib = ctypes.CDLL("./array.so") 
    print lib.test(ss) 

当我运行Python程序,控制台显示错误,错误是“分段错误”。我阅读文档从URL“https://docs.python.org/2/library/ctypes.html”,如何修复该错误。

+0

虽然在Windows上我拷贝了代码,除了向'test'函数中添加'__declspec(dllexport)'并加载.dll而不是.so而且它完美地工作,返回'1'和' 6'。 – 2014-11-01 05:27:34

回答

1

好吧,我知道了,修改后的代码,因为这些:

#include <iostream> 

using namespace std; 

extern "C" 
{ 
struct FirstStructure 
{ 
public: 
    int first_int; 
    int second_int; 
}; 

struct SecondStructure 
{ 
public: 
    int third_int; 
    FirstStructure ft; 
}; 

int test_structure(SecondStructure *ss) 
{ 
    int sum = ss->ft.first_int + ss->ft.second_int + ss->third_int; 
    return sum; 
} 
    int test(SecondStructure *ss) 
    { 
     return test_structure(ss); 
    } 
} 

,然后,我固定的bug。

0

那么如果你打算在C++和python之间设计通信媒介,那么我会建议去组合zmq和google协议缓冲区。

其中proto buf将用于序列化/反序列化和zmq用于通信媒介。

2

你必须在python中声明一个函数的参数和返回类型,以便能够正确地调用它。

所以,调用test函数之前插入以下内容:

lib.test.argtypes = [SecondStructure] 
lib.test.restype = ctypes.c_int 

事情应该工作,那么,据我可以看到... ...

只要C-TO-量python接口仍然是“小”(不管那是什么),我认为​​就好。

+0

我再次遇到了错误。 – 2014-10-31 12:24:45