• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助1

问题说明

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

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

正确答案

#1

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfigak
系列文章
更多 icon
同类精品
更多 icon
继续加载