gpt4 book ai didi

python - 为什么我无法打开/读取从 Python 调用的 C 扩展中的 txt 文件?

转载 作者:行者123 更新时间:2023-12-01 14:47:34 26 4
gpt4 key购买 nike

我尝试将文件名从 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";

.dll 代码在其他情况下正常工作,除非我试图打开/读取 txt 文件或在从 python 调用的 C++ 代码中“打印”一些东西到控制台。
实际上,当我将其编译为 .exe 文件时,它会打开/读取文件并将任何内容打印到控制台都没有问题。

我找不到我的问题的任何解决方案/答案。
也许这里有人可以让我明白我做错了什么?

[编辑#1]
我注意到了一些东西。
当我尝试在 Python3.8 中运行此代码时,我收到以下文件的错误消息:
cygwin1.dll
cygstdc++-6.dll
cyggcc_s-seh-1.dll

即使它们位于 cygwin 的 bin 文件夹中并且 env 路径设置正确,也无法定位。我不得不将这些文件复制粘贴到 example.dll 和 python 包装器 (wrapper.py) 所在的文件夹中。
我不知道这是否与我的问题有关,但我认为值得一提。我开始对那个 cygwin 编译器非常怀疑。挖掘还在继续。

[编辑#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() 行时停止。

最佳答案

两件事一目了然:

  • 您必须确保在函数声明之前使用 __declspec(dllexport) 或通过将其包含在 def 文件中来导出函数。 (如果您到达 fopen 行,这不是问题 - 只是为了完整性而提及。)
  • 您已在 Python 中指定了宽 c 字符串指针 (c_wchar_t),但在 c 中声明了窄 c 字符串 (char*),这些需要匹配。
  • 关于python - 为什么我无法打开/读取从 Python 调用的 C 扩展中的 txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62449158/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com