[英]Trying to open a dll written in c with python ctypes and run the function in it, but it comes as int, not a string
[英]I'm trying to open a dll written in c with python ctypes and run the function in it, but it comes as a char, not a string
這些是我正在處理的代碼:
#include <stdio.h>
void test_print(char test[100])
{
printf("%s", test);
}
from ctypes import *
libcdll = CDLL("test.dll")
libcdll.test_print("test")
但是當我運行程序時,我得到的是“t”而不是“test”。
總是為你的函數設置.argtypes
和.restype
來避免頭痛。 ctypes
可以驗證 arguments 是否正確傳遞。
例子:
測試.c
#include <stdio.h>
__declspec(dllexport) // required for exporting a function on Windows
void test_print(char* test) // decays to pointer, so char test[100] is misleading.
{
printf("%s", test);
}
測試.py
from ctypes import *
libcdll = CDLL("./test")
libcdll.test_print.argtypes = c_char_p, # for (char*) arguments, comma makes a tuple
libcdll.test_print.restype = None # for void return
libcdll.test_print(b"test")
output:
test
如果在 OP 問題中使用“test”調用,現在它會告訴您參數錯誤:
Traceback (most recent call last):
File "C:\test.py", line 5, in <module>
libcdll.test_print("test")
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
Without .argtypes
, ctypes
defaults to converting "test" from a Python str
to a wchar_t*
encoded as UTF-16LE on Windows, so it would look like the following, and printf
will stop at the first null byte ( \x00
), explaining t
作為 output。
>>> 'test'.encode('utf-16le')
b't\x00e\x00s\x00t\x00'
請注意,如果您想傳遞 Python str
而不是bytes
,請聲明 C function 如下並使用.argtypes = c_wchar_p,
:
void test_print(wchar_t* test) {
wprintf(L"%s", test); // wide version of printf and format string
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.