简体   繁体   中英

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

I want to call .NET dll in my python project. I want to use a function which returns string and gets string parameter. But somehow I cant get the string I can just get the first char of the string and sometimes it raises following error:

'charmap' codec can't encode characters in position 1-15: character maps to     <undefined>

EDIT : Solved the error by putting some piece of code.

encode(sys.stdout.encoding, errors='replace')

But this time result is not exactly what I want. Result is : b'h\\xe7\\x8c\\x80' with the input "hello"

Here is my code:

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 function gets string parameter and returns that parameter. But when I run this code it just prints first letter of my parameter.

I found out that c_wchar_p is used for string in python. So I couldn't understand what is the problem with my code.

Any help would be appreciated..

EDIT:

exported dll function:

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

Prototype:

public static string ReturnMyString(string)

If you using Unmanaged Exports its Marshaling Example says ".Net will marshal these strings as single-byte Ansi" by default. If so, use c_char_p and pass byte strings from Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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