在python中使用ctypes从实例访问C#dll的方法

时间:2015-07-17 13:24:05

标签: c# python dllexport

我尝试从website测试示例,但第二个不能工作..我需要创建实例并从实例所在的类调用方法。第一个例子解释为here

似乎我没有得到正确的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`

我在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和属性Name,但我怎么能达到它们:/

1 个答案:

答案 0 :(得分:0)

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