2012-06-19 72 views
0

// Delphi代碼如何從C#中調用delphi dll的指針類型?

procedure SendData(data:pointer;size:cardinal); stdcall; 
    begin 
    c.SendData(data,size); 
    end; 

    function GetEvent(out tag:cardinal):integer; stdcall; 
    begin 
    result:=0; 
    if qEnd<>qStart then begin 
    result:=queue[qStart].eventCode; 
    tag:=queue[qStart].eventTag; 
    inc(qStart); 
    end; 
    end; 

    function GetMessage(handle:cardinal;out data:pointer):cardinal; stdcall; 
    begin 
    result:=GetMsg(handle,data); 
    end; 

我使用unity3d引擎,使用C#從它。我需要整合並調用由delphi創建的dll文件。

所以我在C#中寫道,

using UnityEngine; 
using System.Collections; 
using System; 
using System.Text; 
using System.Collections.Generic; 
using System.Runtime.InteropServices; 

public class test : MonoBehaviour { 
    [DllImport ("ServerTool")] 
    private static extern void Connect(int a); 
    [DllImport ("ServerTool")] 
    private static extern int GetEvent(); 
    [DllImport ("ServerTool")] 
    private static extern void SendData(IntPtr p, int b); 

    // Use this for initialization 
    void Start() { 
     Connect(0); 

     SendData("asdf", 1); 
     Debug.Log(GetEvent()); 
    } 

    // Update is called once per frame 
    void Update() { 

    } 
} 

這發生錯誤說,

資產/ test.cs中(20,17):錯誤1502:對於test.SendData的最佳重載的方法匹配( System.IntPtr,int)有一些無效參數 Assets/test.cs(20,17):錯誤1503:參數/#/ 1無法將字符串表達式轉換爲類型System.IntPtr'

我不知道以及關於德爾福,但指針是類似的C#的對象,不是嗎? 所以我試圖改變IntPtr的反對,然後編譯完成,但是,當運行代碼時,出現錯誤,

MarshalDirectiveException:類型的對象編組未實現 test.Start()(在資產/ test.cs中:20)

那麼我怎麼能從c#中調用上面的delphi的SendData函數呢?

謝謝。

回答

1

你必須使用C#的編組:

在你的情況,你必須將字符串轉換爲一個IntPtr與Marshal.StringToHGlobalAnsi,這需要一個字符串參數,並返回一個IntPtr。

請參閱MSDN文檔:作爲從大衛提到

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx

你也必須使用FreeHGlobal。

+0

當你完成後,別忘了打電話給FreeHGlobal。 –

+0

是啊,你是對的@DavidHeffernan – Lars

0

指針類型應該是OK的。你的整數是錯誤的。 Delphi中的一個基數是32位長的無符號整數(0到4294967295)。 DocWiki Reference

+0

這實際上並不重要,雖然從技術上講你是非常正確的。緩存大於2GB的可能性不大。問題中的問題實際上是編譯時錯誤。 –

+0

哦,我沒有看到編譯器正在抱怨實際的指針類型。 – Manuel

相關問題