2011-03-17 3 views
2

IronPython 2.6에서 Ubuntu 10.10의 C 함수를 pinvoke하려고합니다. 내 모델로 IP 배포판의 예제를 사용했습니다. 그러나 C 코드는 "StandardError : Exception이 호출 대상에 의해 throw되었습니다."Linux에서 IronPython을 Pinvoke하는 방법

여러 접근법을 시도했지만 그 중 아무 것도 작동하지 않습니다. 오브젝트 파일은 "GCC -c pinvoke_test에 의해 컴파일

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

: 여기에 내 코드입니다. c -o pinvoke_test.o "라고합니다. 나는 누군가가 올바른 방향으로 나를 가리킬 수 있기를 바랍니다.

+0

ipy.exe에서 실행할 때 -X : ExceptionDetail을 사용하여 전체 스택 추적을 얻는 것이 좋습니다. 예외 텍스트를 아는 것은 그렇게 유용하지 않습니다. ctypes 라이브러리를 사용하면 C 라이브러리와 더 많은 Pythonic 방식으로 대화 할 수 있기 때문에 운이 좋을 수도 있습니다. –

답변

2

문제의 원인은 아니지만 pinvoke 서명이 잘못 표시됩니다. C 함수는 char가 아닌 char *을 사용합니다.

  1. 이것은 pinvoke 서명의 문자열에 매핑됩니다. 타겟팅하는 플랫폼에 따라 올바른 정렬을 보장하기 위해 CharSet을 지정해야 할 수도 있습니다. http://www.mono-project.com/Interop_with_Native_Libraries#Strings
  2. 이 변경은 'args'변수가 조정될 필요가 있음을 의미합니다. 첫 번째 문자가 아닌 "sample"문자열을 원한다.
  3. 사이드 노트 : C#의 char 유형은 바이트가 아닌 2 바이트 문자에 해당합니다.
관련 문제