可以让Python从C#接收长度可变的字符串数组吗? [英] Can one have Python receive a variable-length string array from C#?

查看:80
本文介绍了可以让Python从C#接收长度可变的字符串数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This may be a red herring, but my non-array version looks like this:

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 []

I am looking for a printstrings, which would fetch a List<string> of variable size. If that's not possible, I will settle for a fixed-length string[].

推荐答案

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

.NET is capable of transforming the object type into COM Automation's VARIANT and the reverse, when going through the p/invoke layer.

VARIANT在 automation.py 中声明rel = noreferrer> comtypes

VARIANT is declared in python's automation.py that comes with comtypes.

Wh使用VARIANT的好处是它可以容纳很多东西,包括许多东西的数组。

What's cool with the VARIANT is it's a wrapper that can hold many things, including arrays of many things.

请记住,您可以像这样声明.NET C#代码

With that in mind, you can declare you .NET C# code like this:

[DllExport("printstrings", CallingConvention = CallingConvention.Cdecl)]
public static void PrintStrings(ref object obj)
{
    obj = new string[] { "hello", "world" };
}

并在python中像这样使用它:

And use it like this in 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)

这篇关于可以让Python从C#接收长度可变的字符串数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆