//delphi code
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;
I am using unity3d engine, using c# from it. And I need to integrate and call dll file created from delphi.
So I wrote in 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 () {
}
}
This occur errors says,
Assets/test.cs(20,17): error 1502: The best overloaded method match for test.SendData(System.IntPtr, int) has some invalid arguments Assets/test.cs(20,17): error 1503: Argument /#/1 cannot convert string expression to type `System.IntPtr'
I don't know well about delphi, but pointer is similar c#'s object, isn't it? So I tried to change IntPtr to object, then compiling is done, but when run the code, error appears,
MarshalDirectiveException: Marshalling of type object is not implemented test.Start () (at Assets/test.cs:20)
Then how can I call above's delphi's SendData function from c#?
Thanks.
You have to use the Marshaling of C#:
In your case you have to convert the String to an IntPtr with Marshal.StringToHGlobalAnsi, which takes a string parameter and returns an IntPtr.
See the MSDN Documentation:
As mentioned from David you also have to use FreeHGlobal.
The pointer type should be OK. Your integer is wrong. A cardinal in Delphi is a 32bit long unsigned integer (0 through 4294967295). DocWiki Reference
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.