.Net dll 函数 returns 只是 Python 中字符串的第一个字符
.Net dll function returns just first char of string in Python
我想在我的 python 项目中调用 .NET dll。我想使用 returns 字符串并获取字符串参数的函数。但不知何故,我无法获取字符串,我只能获取字符串的第一个字符,有时它会引发 以下错误:
'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' 输入 "hello"
这是我的代码:
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 函数获取字符串参数和 returns 该参数。但是当我 运行 这段代码时,它只打印我参数的第一个字母。
我在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)
如果您使用 Unmanaged Exports,其封送处理示例会默认显示“.Net 会将这些字符串封送为单字节 Ansi”。如果是这样,请使用 c_char_p 并从 Python.
传递字节字符串
我想在我的 python 项目中调用 .NET dll。我想使用 returns 字符串并获取字符串参数的函数。但不知何故,我无法获取字符串,我只能获取字符串的第一个字符,有时它会引发 以下错误:
'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' 输入 "hello"
这是我的代码:
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 函数获取字符串参数和 returns 该参数。但是当我 运行 这段代码时,它只打印我参数的第一个字母。
我在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)
如果您使用 Unmanaged Exports,其封送处理示例会默认显示“.Net 会将这些字符串封送为单字节 Ansi”。如果是这样,请使用 c_char_p 并从 Python.
传递字节字符串