วิธีการ Pinvoke IronPython บน Linux

ฉันกำลังพยายามเรียกฟังก์ชัน C จาก IronPython 2.6 บน Ubuntu 10.10 ฉันใช้ตัวอย่างจากการแจกแจง IP เป็นแบบจำลองของฉัน อย่างไรก็ตาม รหัส C แสดง "StandardError: Exception has been Thrown by the target of an invocation"

ฉันได้ลองหลายวิธีแล้ว แต่ก็ไม่ได้ผลเลย นี่คือรหัสของฉัน:

pinvoid_test.h

extern void pinvoke_this(const char*);

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

pinvolve_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 pinvoid_test.c -o pinvoid_test.o" ฉันหวังว่าจะมีคนชี้ฉันไปในทิศทางที่ถูกต้อง


person 0x1mason    schedule 17.03.2011    source แหล่งที่มา
comment
ฉันขอแนะนำให้รับการติดตามสแต็กแบบเต็มโดยใช้ -X:ExceptionDetail เมื่อเรียกใช้จาก ipy.exe แค่รู้ข้อความยกเว้นก็ไม่มีประโยชน์เท่าไหร่ คุณอาจโชคดีกว่าในการใช้ไลบรารี ctypes เนื่องจากเป็นวิธีพูดคุยกับไลบรารี C แบบ Pythonic มากกว่า   -  person Dino Viehland    schedule 18.03.2011


คำตอบ (1)


อาจไม่ใช่สาเหตุของปัญหา แต่ลายเซ็น pinvoid ปรากฏไม่ถูกต้อง ฟังก์ชัน C ของคุณใช้ถ่าน* ไม่ใช่ถ่าน

  1. ซึ่งจะแม็ปกับสตริงในลายเซ็น pinvoid คุณอาจต้องระบุ CharSet เพื่อให้แน่ใจว่าการจัดวางถูกต้อง ขึ้นอยู่กับแพลตฟอร์มที่คุณกำหนดเป้าหมาย ดู http://www.mono-project.com/Interop_with_Native_Libraries#Strings
  2. การเปลี่ยนแปลงนี้จะหมายถึงความต้องการตัวแปร 'args' ของคุณที่ได้รับการปรับเปลี่ยนเช่นกัน คุณต้องการสตริง "sample" ไม่ใช่อักขระตัวแรก
  3. หมายเหตุด้านข้าง: ประเภทถ่านใน C# สอดคล้องกับอักขระ 2 ไบต์ ไม่ใช่ไบต์
person joncham    schedule 31.03.2011