我想在我的python项目中调用 .NET dll。我想使用一个返回字符串并获取字符串参数的函数。但不知怎的,我不能得到字符串我可以得到字符串的第一个字符串,有时它会引发跟随错误:
'charmap' codec can't encode characters in position 1-15: character maps to <undefined>
编辑:通过放置一些代码来解决错误。
encode(sys.stdout.encoding, errors='replace')
但这次结果并不完全是我想要的。结果是: b&#39; h \ xe7 \ x8c \ x80&#39; 输入&#34;你好&#34;
这是我的代码:
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)
答案 0 :(得分:1)
如果您使用非托管导出,其封送示例会说&#34; .Net会将这些字符串封送为单字节Ansi&#34;默认情况下。如果是这样,请使用c_char_p并从Python传递字节字符串。