可以让Python从C#接收一个可变长度的字符串数组吗?

Dim*_*rob 9 c# python dll ctypes

这可能是一个红色的鲱鱼,但我的非阵列版本看起来像这样:

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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

蟒蛇

import ctypes
dll = ctypes.cdll.LoadLibrary(“test.dll")
dll.printstring.restype = ctypes.c_char_p
dll.printstring()
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个printstrings可以获取List<string>可变大小的a.如果那是不可能的话,我会解决一个固定长度string[].

Sim*_*ier 8

当通过p/invoke层时,.NET能够将object类型转换为COM自动化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" };
}
Run Code Online (Sandbox Code Playgroud)

并在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)
Run Code Online (Sandbox Code Playgroud)