我尝试将文件名从python传递到C \ C ++ .dll,并使C \ C ++代码打开/读取该文件。
这是我尝试使用ctypes实现的一个非常简单的示例。请原谅我的C ++代码。我在这里学习
//C++ code in example.cpp compiled to example.dll
#include <stdio.h>
extern "C" {
char* _line;
char* test(char* txt){
FILE* f_name;
f_name = fopen(txt, "r");
//... read data from file and do something
_line = txt;
return _line; // this is just my sanity check to see if "file.txt" got passed from python
}
}
我使用cygwin-64将其编译为.dll:
g++ -fPIC -shared example.cpp -o example.dll
Python包装器:
import ctypes
print("works!") #just sanity check...
lib = ctypes.CDLL("example.dll")
cpp_file_access = lib.test
cpp_file_access.argtypes = [ctypes.c_char_p]
cpp_file_access.restype = ctypes.c_char_p
print(cpp_file_access(b"file.txt")) #sanity check to see if file name got passed
从Python调用.dll中的test()时,程序不会越过以下行:
f_name = fopen(txt, "r");
无论我使用哪种方法打开/访问所述txt文件。它要么“挂起”并且不执行任何操作,要么抛出WindowsError指示访问冲突0x00000(...)。当我在C ++代码中使用任何类型的“打印”功能时,都会发生相同的行为,例如:
printf("test print !");
std::cout << "another test print";
除非我尝试打开/读取txt文件或使用从python调用的C ++代码将某些内容“打印”到控制台,否则.dll代码在其他情况下也可以正常工作。实际上,当我将其编译为.exe文件时,它将打开/读取文件并向控制台打印任何内容,都没有问题。
我找不到我的问题的任何解决方案/答案。也许这里有人可以启发我我做错了什么?
[EDIT#1]我注意到了一些事情。当我尝试在Python3.8中运行此代码时,出现以下错误消息:
cygwin1.dll
cygstdc++-6.dll
cyggcc_s-seh-1.dll
即使它们位于cygwin的bin文件夹中并且环境路径设置正确也无法找到。我必须将这些文件复制粘贴到example.dll和python wrapper(wrapper.py)所在的文件夹中。我不知道这与我的问题是否有关,但我认为值得一提。我开始对该cygwin编译器非常怀疑。继续挖掘。
[EDIT#2]我通过添加void test_2()修改了C ++代码,因此在python和.dll之间没有传递参数。
__declspec(dllexport) void test_2(){
FILE* f_name;
f_name = fopen("file.txt", "r");
}
并从python调用它:
void_acc = lib.test_2
void_acc.restype = None
void_acc()
print ("program ended, go away !") // .. sanity check
问题依旧。到达fopen()行时,程序执行停止。
解决了。
毕竟是编译器问题。我应该使用mingw-64位而不是cygwin。
我按照这段视频中的指示进行操作:https : //www.youtube.com/watch?v=aXF4A5UeSeM
工作良好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句