使用 ctypes 来自 .dll 的 python 中的 C++ 函数 - 找不到函数和访问冲突
C++ function in python from .dll using ctypes - function not found and access violation
我有一个名为 hello.cpp
的简单 C++ 代码,它具有打印 "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) 使用:
g++ -c hello.cpp
g++ -static -fPIC -o hello.dll hello.o
(尝试在 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"
也是如此,这样代码就不会得到 "mangled"。所以现在使用它作为代码:
#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++ 函数?我可以跳过中间人并以某种方式 运行 来自 .cpp 文件或 .o 文件的 C++ 函数吗?
编辑:
根据eryksun的回答,原来不需要dllexport。 extern "C" 是必须的
感谢@eryksun,在这种情况下通过如下编译解决了这个问题:
g++ -c hello.cpp
g++ -static -shared -o hello.dll hello.o
像这样设置 C++ 代码:
#include <iostream>
int main() {
std::cout << "Opened" << std::endl;
}
void hello_world() {
std::cout << "hello world" << std::endl;
}
extern "C" {
void hello_world();
}
和 运行 它像往常一样来自 Python:
from ctypes import cdll
lib = cdll.LoadLibrary('hello.dll')
lib.hello_world()
我有一个名为 hello.cpp
的简单 C++ 代码,它具有打印 "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) 使用:
g++ -c hello.cpp
g++ -static -fPIC -o hello.dll hello.o
(尝试在 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"
也是如此,这样代码就不会得到 "mangled"。所以现在使用它作为代码:
#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++ 函数?我可以跳过中间人并以某种方式 运行 来自 .cpp 文件或 .o 文件的 C++ 函数吗?
编辑:
根据eryksun的回答,原来不需要dllexport。 extern "C" 是必须的
感谢@eryksun,在这种情况下通过如下编译解决了这个问题:
g++ -c hello.cpp
g++ -static -shared -o hello.dll hello.o
像这样设置 C++ 代码:
#include <iostream>
int main() {
std::cout << "Opened" << std::endl;
}
void hello_world() {
std::cout << "hello world" << std::endl;
}
extern "C" {
void hello_world();
}
和 运行 它像往常一样来自 Python:
from ctypes import cdll
lib = cdll.LoadLibrary('hello.dll')
lib.hello_world()