用cType从C++函数返回字符串,给出大的int,而不是字符

2024-10-01 07:51:08 发布

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

我试图用Python中的cType从DLL调用C++函数。我当前的问题是该函数似乎返回一个大整数,要么是正的,要么是负的,而不是我期望它返回的char指针。如果我把这个int转换成一个c_char_p并调用它的.value,它每次都会杀死我的内核。我在这个网站和文档里都找遍了,但还是搞不懂。我在这个网站上看到的很多东西甚至会给我带来错误,比如在ctypes对象和函数应该是字节对象或类似对象时,向它们传递字符串。下面是转换成dll的c++代码和我用来从dll调用函数的python代码。如果有人能帮我,那就太棒了。sayshomething是我们讨论的函数。谢谢。在

测试库.h

#pragma once

#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllexport)
#endif

#include <windows.h>
#include <cstring>

#ifdef __cplusplus
extern "C"
{
#endif

    TESTLIBRARY_API char* SaySomething(const char* phrase);

#ifdef __cplusplus
};
#endif

在测试库.cpp在

^{pr2}$

测试仪2.py

import ctypes

dbl = ctypes.c_double
pChar = ctypes.c_char_p
pVoid = ctypes.c_void_p

libName = (r"D:\Documents\Coding Stuff\Visual Studio 2017\Projects\TestLibrary"
           r"Solution\x64\Debug\TestLibrary.dll")
x = ctypes.windll.LoadLibrary(libName)

x.SaySomething.argtypes = [pChar]
x.SaySomething.restypes = pChar

phrase = b"Hi"
phrase = pChar(phrase)

res = x.SaySomething(phrase)

Tags: 对象函数代码api网站plusctypesdll
1条回答
网友
1楼 · 发布于 2024-10-01 07:51:08

你现在可以做的是一个API泄漏。更好的解决方案是让Python为结果分配和管理内存。在

我还修复了注释中提到的dllimport,并在.cpp文件中定义了TESTLIBRARY_EXPORTS,这样函数就可以从DLL中导出了。restype也被修复了。在

TesterLibrary.h

#pragma once

#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllimport)
#endif

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#ifdef __cplusplus
extern "C" {
#endif

TESTLIBRARY_API char* SaySomething(const char* phrase, char* result, size_t resultMaxLength);

#ifdef __cplusplus
}
#endif

测试工具库.cpp

^{pr2}$

tester2.py

import ctypes

libName = (r"TestLibrary.dll")
x = ctypes.CDLL(libName)

x.SaySomething.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.c_size_t]
x.SaySomething.restype = ctypes.c_char_p

phrase = b"Hi"
result = ctypes.create_string_buffer(100)
res = x.SaySomething(phrase,result,ctypes.sizeof(result))
print(res)
print(result.value)

输出

b'Decorated <Hi>'
b'Decorated <Hi>'

当不再有对result缓冲区的引用时,Python将自动释放它。在

相关问题 更多 >