【问题标题】:How to Pinvoke IronPython on Linux如何在 Linux 上 Pinvoke IronPython
【发布时间】:2011-03-17 17:46:14
【问题描述】:

我正在尝试在 Ubuntu 10.10 上从 IronPython 2.6 调用 C 函数。我使用了 IP 分发中的一个示例作为我的模型。但是,C 代码会抛出“StandardError: Exception has been throwed by the target of an invocation.”

我尝试了几种方法,但都没有奏效。这是我的代码:

pinvoke_test.h

extern void pinvoke_this(const char*);

pinvoke_test.c

#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);
}

pinvoke_test.py

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

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

【问题讨论】:

  • 我建议在从 ipy.exe 运行时使用 -X:ExceptionDetail 获取完整的堆栈跟踪。仅仅知道异常文本并不是那么有用。使用 ctypes 库可能会更好,因为它是一种与 C 库对话的更 Pythonic 的方式。

标签: linux mono pinvoke ironpython


【解决方案1】:

这可能不是您的问题的原因,但 pinvoke 签名出现错误。您的 C 函数采用 char*,而不是 char。

  1. 这会映射到 pinvoke 签名中的字符串。您可能需要指定 CharSet 以确保正确编组,具体取决于您的目标平台。见http://www.mono-project.com/Interop_with_Native_Libraries#Strings
  2. 此更改将意味着您的“args”变量也需要调整。您需要字符串“sample”,而不是第一个字符。
  3. 旁注:C# 中的 char 类型对应的是 2 字节字符,而不是字节。

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多