[英]Can one have Python receive a variable-length string array from C#?
這可能是一個紅色的鯡魚,但我的非陣列版本看起來像這樣:
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";
}
}
}
蟒蛇
import ctypes
dll = ctypes.cdll.LoadLibrary(“test.dll")
dll.printstring.restype = ctypes.c_char_p
dll.printstring()
我正在尋找一個可以獲取可變大小的List<string>
的printstrings
。 如果那是不可能的,我會選擇一個固定長度的string[]
。
當能夠通過p / invoke層時,.NET能夠將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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.