可以让Python从C#接收一个可变长度的字符串数组吗?
这可能是一个红色的鲱鱼,但我的非arrays版本看起来像这样:
C#
using RGiesecke.DllExport; using System.Runtime.InteropServices; namespace Blah { public static class Program { [DllExport("printstring", CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.AnsiBStr)] public static string PrintString() { return "Hello world"; } } }
python
import ctypes dll = ctypes.cdll.LoadLibrary(“test.dll") dll.printstring.restype = ctypes.c_char_p dll.printstring()
我正在寻找一个可以获取可变大小的List
的printstrings
。 如果那是不可能的,我会选择一个固定长度的string[]
。
.NET能够在通过p / invoke层时将object
类型转换为COM Automation的VARIANT
,反之亦然。
VARIANT在python的automation.py
中声明,它带有comtypes
。
VARIANT的优点在于它是一个可以容纳许多东西的包装器,包括许多东西的数组。
考虑到这一点,您可以像这样声明.NET C#代码:
[DllExport("printstrings", CallingConvention = CallingConvention.Cdecl)] public static void PrintStrings(ref object obj) { obj = new string[] { "hello", "world" }; }
并在python中使用它:
import ctypes from ctypes import * from comtypes.automation import VARIANT dll = ctypes.cdll.LoadLibrary("test") dll.printstrings.argtypes = [POINTER(VARIANT)] v = VARIANT() dll.printstrings(v) for x in v.value: print(x)