gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:22:23 25 4
gpt4 key购买 nike

这可能是一个转移注意力的问题,但我的非数组版本看起来像这样:

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()

我正在寻找 printstrings ,这将获取 List<string>可变大小。如果那不可能,我将接受固定长度的 string[] .

最佳答案

.NET 能够将 object 类型转换为 COM Automation 的 VARIANT反之,当通过 p/invoke 层时。

VARIANT 在comtypes 附带的python 的automation.py 中声明。 .

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)

关于c# - 可以让 Python 从 C# 接收可变长度的字符串数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48389060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com