2011-03-17 53 views
2

我試圖在Ubuntu 10.10上從IronPython 2.6中調用C函數。我使用了來自IP分配的示例作爲我的模型。但是,C代碼會拋出「StandardError:異常已被調用的目標拋出。」如何在Linux上拼音IronPython

我已經嘗試了幾種方法,但都沒有工作。這裏是我的代碼:

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「。我希望有人能指出我正確的方向。

+0

我建議使用-X:ExceptionDetail從ipy.exe運行時獲取完整的堆棧跟蹤。只知道例外文本並不是那麼有用。使用ctypes庫也可能會有更好的運氣,因爲它是與C庫交談的更加Pythonic的方式。 – 2011-03-18 01:39:34

回答

2

它可能不是你問題的原因,但pinvoke簽名出現錯誤。你的C函數需要一個char *,而不是char。

  1. 這映射到pinvoke簽名中的字符串。您可能需要指定CharSet以確保正確編組,這取決於您定位的平臺。請參閱http://www.mono-project.com/Interop_with_Native_Libraries#Strings
  2. 此更改意味着您的'參數'變量需求也會調整。你需要字符串「sample」,而不是第一個字符。
  3. 備註:C#中的字符類型對應於2字節字符,而不是字節。