[英]How do I call this Delphi method in C# using Dllimport?
新程序員需要幫助!
編譯到DLL中的Delphi代碼
function SetCurrentSerial(Size : Integer; Msg : Pointer) : Integer stdcall;
var
TempByte : PByte;
TempStr : string;
i: Integer;
begin
Result := 0;
TempByte := Msg;
TempStr := '';
for i := 0 to Size - 1 do
begin
TempStr := TempStr + ' ';
end;
for i := 0 to Size - 1 do
begin
TempStr[i+1] := Chr(TempByte^);
Inc(TempByte);
end;
if not DLLClass.SelectDeviceSerial(TempStr) then
begin
Result := -1;
end;
end;
C#代碼
//Import a Function Pointer
[DllImport("Test.dll", CallingConvention= CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public unsafe static extern int SetCurrentSerial(int Size, byte[] Msg);
我需要將指針值,大小和消息存儲在緩沖區中,然后在控制台窗口中打印該值。
我將不勝感激完整構建的代碼。 先感謝您。
這是我到目前為止嘗試過的代碼。 // C#代碼
class Program
{
[DllImport("Test.dll")]
public unsafe static extern int SetCurrentSerial(int Size, void* Msg);
unsafe static void Main()
{
int Res;
byte[] buffer = new byte[1024];
Res = SetCurrentSerial(255, &buffer);
Console.WriteLine("%s\n", buffer);
}
}
您的DLL函數設計不正確。 您正在將字符串從調用代碼傳遞到DLL。 這真的很簡單,您可以刪除幾乎所有代碼。 Delphi代碼應如下所示:
function SetCurrentSerial(Serial: PAnsiChar): LongBool; stdcall;
begin
Result := DLLClass.SelectDeviceSerial(Serial);
end;
然后,C#代碼應為:
[DllImport("Test.dll", CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Ansi)]
public static extern bool SetCurrentSerial(string Serial);
像這樣調用函數:
bool succeeded = SetCurrentSerial(Serial);
if (!succeeded)
{
// handle error
}
我已經用指示成功或失敗的布爾值替換了您的整數返回值。 您是否希望還原為如下所示的整數:
德爾福
function SetCurrentSerial(Serial: PAnsiChar): Integer; stdcall;
begin
if DLLClass.SelectDeviceSerial(Serial) then begin
Result := 0;
end else begin
Result := -1;
end;
end;
C#
[DllImport("Test.dll", CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Ansi)]
public static extern int SetCurrentSerial(string Serial);
更新
顯然,您不能更改此DLL。 真可惜,因為它的設計和實現確實非常糟糕。 但是,要從C#調用該函數,您需要像這樣聲明p / invoke:
[DllImport("Test.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int SetCurrentSerial(int Size, byte[] Msg);
然后這樣稱呼它:
byte[] Msg = Encoding.Default.GetBytes(serial);
int retval = SetCurrentSerial(Msg.Length, Msg);
if (retval != 0)
{
// handle error
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.