如何在Linux上使用Pinvoke IronPython

如何在Linux上使用Pinvoke IronPython,linux,mono,pinvoke,ironpython,Linux,Mono,Pinvoke,Ironpython,我正在尝试在Ubuntu10.10上使用IronPython2.6的C函数。我使用了一个来自IP分发的示例作为我的模型。但是,C代码抛出“StandardError:调用目标已抛出异常” 我试过几种方法,但都不管用。这是我的密码: pinvoke_试验 extern void pinvoke_this(const char*); pinvoke_试验 #include <stdio.h> #include "pinvoke_test.h" void pinvoke_this(co

我正在尝试在Ubuntu10.10上使用IronPython2.6的C函数。我使用了一个来自IP分发的示例作为我的模型。但是,C代码抛出“StandardError:调用目标已抛出异常”

我试过几种方法,但都不管用。这是我的密码:

pinvoke_试验

extern void pinvoke_this(const char*);
pinvoke_试验

#include <stdio.h>
#include "pinvoke_test.h"

void pinvoke_this(const char *b)
{
    FILE *file;
    file = fopen("file.txt","w+");
    fprintf(file,"%s", b);
    fclose(file);
}

目标文件由“gcc-c pinvoke_test.c-o pinvoke_test.o”编译。我希望有人能给我指出正确的方向

这可能不是问题的原因,但pinvoke签名似乎是错误的。您可以使用C函数获取字符*,而不是字符

  • 这映射到pinvoke签名中的字符串。您可能需要指定字符集以确保正确编组,具体取决于您所针对的平台。看
  • 此更改意味着您的“args”变量也需要调整。您需要字符串“sample”,而不是第一个字符
  • 旁注:C#中的字符类型对应于一个2字节字符,而不是一个字节
    我建议在从ipy.exe运行时使用-X:ExceptionDetail获取完整的堆栈跟踪。仅仅知道异常文本并没有多大用处。使用ctypes库可能会更幸运,因为它是一种与C库对话的更具Python风格的方式。
    import clr
    import clrtype
    import System
    
    class NativeMethods(object):
    
        __metaclass__ = clrtype.ClrClass
    
        from System.Runtime.InteropServices import DllImportAttribute, PreserveSigAttribute
        DllImport = clrtype.attribute(DllImportAttribute)
        PreserveSig = clrtype.attribute(PreserveSigAttribute)
    
        @staticmethod
        @DllImport("pinvoke_test.o")
        @PreserveSig()
        @clrtype.accepts(System.Char)
        @clrtype.returns(System.Void)
        def pinvoke_this(c): raise RuntimeError("this should not get called")
    
    
    def call_pinvoke_method():
        args = System.Array[object](("sample".Chars[0],))
        pinvoke_this = clr.GetClrType(NativeMethods).GetMethod('pinvoke_this')
        pinvoke_this.Invoke(None, args)
    
    call_pinvoke_method()