linux - 如何在 Linux 上调用 IronPython

标签 linux mono pinvoke ironpython

我正在尝试在 Ubuntu 10.10 上从 IronPython 2.6 调用一个 C 函数。我使用了 IP 分配中的一个示例作为我的模型。但是,C 代码抛出“StandardError:调用目标已抛出异常。”

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

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”编译。我希望有人能指出我正确的方向。

最佳答案

这可能不是您问题的原因,但 pinvoke 签名似乎有误。您的 C 函数接受一个 char*,而不是一个 char。

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

关于linux - 如何在 Linux 上调用 IronPython,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5343051/

相关文章:

php - URL 的 fopen() 中断域名,而不是数字地址

用于 Linux 和/或 MonoDevelop 的 C# 代码格式化程序

php - 不同的操作系统和服务器路径

linux - 如何在 shell 脚本中获取命令的输出?

linux - 256 色终端中的单声道控制台应用程序

mysql - 对现有用户使用 MySql ASP.NET 成员资格提供程序

c# - 来自 LLVM 绑定(bind)的不平衡堆栈警告

C# 调用返回具有固定大小 char 数组的结构的 C 函数

c# - 如何在 NuGet 包中包含一个 pinvoked dll?

linux - Linux time 命令输出中 real、user 和 sys 的含义