使用cython包装c++DLL:所有字符串都是空的

2024-09-27 00:16:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用cython包装用c++编写的DLL。最终我将无法访问 源代码,所以在编译包装器的过程中不能使用c++源代码,它包含.dll.lib和{}。 一切都很顺利。 然而,我立刻发现弦的表现并不好。例如,dll 返回简单字符串的函数不能正常工作:cython代码总是获得 空字符串。我在Windows7上。我已经核实了以下内容。在

  • DLL是由visualstudio2015(即v1900)用调试中的2015工具集构建的 模式。我尝试了使用/MTd和/MDd标志进行编译。生成的.lib和.dll文件是 与下面所有其他文件放在同一个文件夹中。在
  • 我的python3.5发行版也是由vs2015构建的,为32位。在

    $ python -iu
    Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
    
  • 当我使用一个包含返回字符串的函数的伪c++源代码进行编译时, 它只是起作用。使用dll它不起作用。

在设置.py公司名称:

^{pr2}$

在测试.pyx公司名称:

# distutils: language = c++
# distutils: libraries = MyDLL
# distutils: include_dirs = .
# distutils: library_dirs = .
from libcpp.string cimport string

cdef extern from "MyDLL.h" namespace "somenamespace":

    int ReturnSomeInt()
    string ReturnSomeString()

def run():
    cdef string s = string(b'abcdefg')
    print(s)
    cdef int i = ReturnSomeInt()
    print(i)
    cdef string problem = ReturnSomeString()
    print(problem)

MyDLL.h:

__declspec(dllexport) int ReturnSomeInt();
__declspec(dllexport) std::string ReturnSomeString();

编译MyDL:

的C++代码片段
__declspec(dllexport) int ReturnSomeInt() { return 42; }
__declspec(dllexport) std::string ReturnSomeString() { cout << "debug..." << endl; return "Hello world!"; }

在主.py公司名称:

from test import run
run()

我使用命令编译

$ python setup.py build_ext --inplace --force && python -u main.py

打印出这个

b'abcdefg'
42
debug... # printed by the dll function ReturnSomeString()
b'' # Should've printed: b'Hello World!'

我们可以验证MyDLL中的ReturnSomeString()是否被实际调用,因为它向stdout发送了一些文本。在

我没查到什么?在


Tags: 字符串py名称string源代码公司intdll
1条回答
网友
1楼 · 发布于 2024-09-27 00:16:29

感谢@hakala指出的this answer,我发现调试/发布模式很重要。我没想到会这样。我引用:

The C++ standard library has its own set of ABI issues. There is no guarantee that a given STL type is laid out the same way in memory, nor is there a guarantee that a given STL class has the same size from one implementation to another (in particular, debug builds may put extra debug information into a given STL type). Therefore, any STL container will have to be unpacked into fundamental types before being passed across the DLL boundary and repacked on the other side.

实际上,在Release模式下编译DLL使OP中的示例起作用。在

相关问题 更多 >

    热门问题