在python中使用ctypes从实例中访问c# dll's方法

本文关键字:dll 方法 实例 python ctypes 访问 | 更新日期: 2023-09-27 18:03:18

我试着从网站测试的例子,但第二个不会工作。我需要创建实例并从实例所在的类调用方法。第一个例子在这里解释。

似乎我没有得到正确的python代码:/到达指针对象背后的方法和属性..

这是c# dll

[ComVisible(true)] 
[Guid("0000000a-000b-000c-0001-020304050607"), 
 InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISample
{
   // without MarshalAs(UnmanagedType.BStr), .Net will marshal these strings as single-byte Ansi!
   // BStr is equivalent to Delphi's WideString
   String Name
   {
     // this is how to add attributes to a getter's result parameter
     [return: MarshalAs(UnmanagedType.BStr)]
     get;
     // this is how to add attributes to a setter's value parameter
     [param: MarshalAs(UnmanagedType.BStr)]
     set;
   }
   int DoSomething(int value);
}
public class Sample : ISample
{
   public String Name{ get; set; }
   public int DoSomething(int value)
   {
     return value + 1;
   }
}
static class Exports
{
   [DllExport]
   public static void CreateSampleInstance([MarshalAs(UnmanagedType.Interface)]out ISample instance)
   {
     instance = new Sample{ Name = "Test" };
   }
}`enter code here`

i tried in python shell

>>>import ctypes
>>>a=ctypes.cdll.LoadLibrary(source)
>>>b=a.CreateSampleInstance
>>>b
<_FuncPtr object at 0x028E65D0>
>>>b.Name 
Traceback (most recent call last):
  File "<pyshell#85>", line 1, in <module>
    instance.Name
AttributeError: '_FuncPtr' object has no attribute 'Name'

当然,指针不能知道方法DoSomething和属性名称,但我怎么能到达他们:/

在python中使用ctypes从实例中访问c# dll's方法

我建议你看一下IronPython (http://ironpython.net/),特别是http://ironpython.net/documentation/dotnet/dotnet.html#id31