0
我想在我的python項目中調用.NET dll。我想使用返回字符串並獲取字符串參數的函數。通過把一些代碼段解決的錯誤:但不知何故,我不能得到字符串我就可以得到字符串的第一個字符,有時以下錯誤引發:.Net dll函數返回Python中字符串的第一個字符
'charmap' codec can't encode characters in position 1-15: character maps to <undefined>
編輯。
encode(sys.stdout.encoding, errors='replace')
但是這次結果並不是我想要的。結果是:b'h \ XE7 \ x8c \ X80'與輸入「你好」
這裏是我的代碼:
import ctypes
import time
hllDll = ctypes.WinDLL ("C:\\Users\\yazilimhpaio2\\Downloads\\mydll.dll")
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_wchar_p, # Return type.
ctypes.c_wchar_p # Parameter 1 ...
)
hllApiParams = (1,"p1",0),
hllApi = hllApiProto (("ReturnMyString", hllDll), hllApiParams)
var = "hello"
p1 = ctypes.c_wchar_p (var)
x = hllApi (p1)
print(x.encode(sys.stdout.encoding, errors='replace'))
time.sleep(3)
ReturnMyString函數獲取字符串參數並返回參數。但是當我運行這個代碼時,它只是打印我的參數的第一個字母。
我在python中發現c_wchar_p is used for string。 所以我不明白我的代碼有什麼問題。
任何幫助,將不勝感激..
編輯:
導出的DLL函數:
[ComVisible(true)]
[DllExport("ReturnMyString", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
public static string ReturnMyString(string value)
{
return value;
}
原型:
public static string ReturnMyString(string)
你試圖調用的C函數的原型是什麼?如果需要'char *',使用'c_char_p',如果它需要'wchar_t *'使用'c_wchar_p'。我懷疑它是前者。如果是這樣,不要傳遞一個Python 3字符串,但使用一個字節字符串......例如'b'hello'。 –
@MarkTolonen該DLL是用C#編寫的,因此它只接受字符串並返回字符串。 – Hilal
然後顯示如何導出DLL函數。顯示原型。你仍然需要導出一個C原型來從'ctypes'調用它。如果您只看到第一個字符,則暗示應該使用'c_char_p',因爲'c_wchar_p'會將該字符串作爲''h \ x00e \ x00l \ x00l \ x00o \ x00''傳遞並且在第一個字節之後看起來爲空。 –