This is the reverse/complement of this question.
I am using Unmanaged Exports and ctypes, and want to pass a variable-length list of strings from Python to C#, and get a string back.
I try four C# + Python variants - none succeeds. Can anyone get the job done?
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());
}
Python
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