繁体   English   中英

.NET DLL函数仅在Python中返回字符串的第一个字符

[英].Net dll function returns just first char of string in Python

我想在我的python项目中调用.NET dll。 我想使用一个返回字符串并获取字符串参数的函数。 但是以某种方式我无法获取字符串,我只能获取字符串的第一个字符,有时会引发以下错误:

'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函数获取字符串参数并返回该参数。 但是,当我运行此代码时,它只会打印参数的首字母。

我发现c_wchar_p用于 python中的字符串 所以我不明白我的代码是什么问题。

任何帮助,将不胜感激..

编辑:

导出的dll函数:

[ComVisible(true)]
[DllExport("ReturnMyString", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
public static string ReturnMyString(string value)
{
    return value;
}

原型:

public static string ReturnMyString(string)

如果使用“非托管导出”,则其编组示例默认情况下会显示“ .Net将把这些字符串编组为单字节Ansi”。 如果是这样,请使用c_char_p并从Python传递字节字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM