[英]Can one have Python send a variable-length string array to C#?
這是這個問題的反面/補充。
我正在使用Unmanaged Exports和ctypes ,並希望將可變長度的字符串列表從Python傳遞到C#,然后返回一個字符串。
我嘗試了四種C#+ Python變體-沒有成功。 誰能完成工作?
C#
/* no ref, convert to list */
[DllExport("combineWords1", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.AnsiBStr)]
public static string CombineWords1(object obj)
{
var l = (List<string>) obj;
return string.Join(",", l.ToArray());
}
/* no ref, convert to array */
[DllExport("combineWords2", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.AnsiBStr)]
public static string CombineWords2(object obj)
{
var l = (string[]) obj;
return string.Join(",", l);
}
/* ref, convert to list */
[DllExport("combineWords3", CallingConvention = CallingConvention.Cdecl)]
public static void CombineWords3(ref object obj)
{
var l = (List<string>)obj;
obj = string.Join(",", l.ToArray());
}
/* ref, convert to array */
[DllExport("combineWords4", CallingConvention = CallingConvention.Cdecl)]
public static void CombineWords4(ref object obj)
{
var l = (string[]) obj;
obj = string.Join(",", l.ToArray());
}
蟒蛇
import ctypes
from comtypes.automation import VARIANT
dll = ctypes.cdll.LoadLibrary("<...>")
l = ["Hello", "world"]
# 1
dll.combineWords1.argtypes = [ctypes.POINTER(VARIANT)]
dll.combineWords1.restype = ctypes.c_char_p
obj = VARIANT(l)
dll.combineWords1(obj)
#WindowsError: [Error -532462766] Windows Error 0xE0434352
# 2
dll.combineWords2.argtypes = [ctypes.POINTER(VARIANT)]
dll.combineWords2.restype = ctypes.c_char_p
obj = VARIANT(l)
dll.combineWords2(obj)
# WindowsError: [Error -532462766] Windows Error 0xE0434352
# 3
dll.combineWords3.argtypes = [ctypes.POINTER(VARIANT)]
obj = VARIANT(l)
dll.combineWords3(obj)
#WindowsError: [Error -532462766] Windows Error 0xE0434352
# 4
dll.combineWords4.argtypes = [ctypes.POINTER(VARIANT)]
obj = VARIANT(l)
dll.combineWords4(obj)
#WindowsError: [Error -532462766] Windows Error 0xE0434352
您可以像這樣聲明C#端:
[DllExport("combinewords", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPWStr)] // matches python's c_wchar_p
public static string CombineWords(object obj) // object matches python's VARIANT
{
var array = (object[])obj; // if obj is an array, it will always be an array of object
return string.Join(", ", array);
}
而python方面是這樣的:
import ctypes
from ctypes import *
from comtypes.automation import VARIANT
dll = ctypes.cdll.LoadLibrary("exported") # the dll's name
dll.combinewords.argtypes = [VARIANT] # python VARIANT = C# object
dll.combinewords.restype = ctypes.c_wchar_p
# create a VARIANT from a python array
v = VARIANT(["hello", "world"])
print(dll.combinewords(v))
注意:我曾經使用unicode聲明,但效果更好。 Ansi已成為過去。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.