Python中的C++函数,使用未找到的cType函数和访问冲突

2024-04-16 17:31:16 发布

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

我有一个简单的C++代码,名为^ {CD1>},它具有打印“Hello World”

的功能。
#include <iostream>

void hello_world();

int main() {
    std::cout << "Start" << std::endl;
}

void hello_world() {
    std::cout << "Hello world" << std::endl;
}

我使用以下方法构建.dll(~1.9mb):

^{pr2}$

(当尝试在python中访问时,使用-shared会给出一个WinError 126 ... module not found

python代码是:

from ctypes import cdll

lib = cdll.LoadLibrary('hello.dll')
lib.hello_world()

这将引发以下错误:

AttributeError: function 'hello_world' not found

我读过有人提到__declspec(dllexport)包装是必要的,而且extern "C"也是必要的,这样代码就不会“损坏”。所以现在用它作为代码:

#include <iostream>

extern "C" {
    __declspec(dllexport) void hello_world();
}

int main() {
    std::cout << "Opened" << std::endl;
}


void hello_world() {
    std::cout << "hello world" << std::endl;
}

python行lib.hello_world()现在将引发:

OSError: exception: access violation writing 0x000E28A0

这里有什么问题?如何获取Python来识别和运行.dll中的C++函数?我能跳过中间人,不知何故从.cp文件或.o文件中运行C++函数吗?在

编辑:

使用eryksun的答案,结果发现dllexport不需要。外部“C”是必须的


Tags: 代码helloworldincludemainlibintdll
1条回答
网友
1楼 · 发布于 2024-04-16 17:31:16

感谢@eryksun,在本例中,通过如下编译解决了这个问题:

g++ -c hello.cpp
g++ -static -shared -o hello.dll hello.o

C++代码的设置与SO:

^{pr2}$

像往常一样从Python运行它:

from ctypes import cdll

lib = cdll.LoadLibrary('hello.dll')
lib.hello_world()

相关问题 更多 >