Can one have Python receive a variable-length string array from C#?

后端 未结 1 1740
孤独总比滥情好
孤独总比滥情好 2021-01-04 20:38

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

C#

using RGiesecke.DllExport;
using System.Runtime.InteropServi         


        
相关标签:
1条回答
  • 2021-01-04 21:12

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

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

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

    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" };
    }
    

    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)
    
    0 讨论(0)
提交回复
热议问题