标签:
在用Delphi封装Dll的时候,参数为Pchar,接口函数如下:
function TestDll(priKey, oldStr, newStr: PChar): Integer; stdcall;
其中第三个参数newStr,为返回参数,现有两种写法:
1、指针传递,分配内存空间,传入指针地址,改变所指向内容;
function TestDll(priKey, oldStr, newStr: PChar): Integer; stdcall; var sTemp: string; begin Result := -1; stemp := ‘Hello‘; StrCopy(newStr, PChar(sTemp)); Result := 0; end;
Delphi调用:
procedure TForm1.Button1Click(Sender: TObject); var macdll: THandle; Encry: function(priKey, oldStr, newStr: PChar): Integer; stdcall; nvalue: PChar; begin macdll := LoadLibrary(‘test.dll‘); if macdll <> 0 then begin @Encry := GetProcAddress(macdll, ‘TestDll‘); if @Encry <> nil then begin nvalue := StrAlloc(255);; Encry(‘test1‘, ‘test2‘, nvalue); ShowMessage(StrPas(nvalue)); end; FreeLibrary(macdll); end; end;
C++调用:char* param2(指针)
char output[1024] = { 0 }; typedef int(__stdcall *TestDll)(char* pKey, char* param1, char* param2); TestDll pFun = (TestDll)GetProcAddress(hModule, "TestDll"); if (pFun) { pFun("test1", "test2", output); }
2、指针引用传递,传入指针,改变指针本身;
function TestDll(priKey, oldStr:PChar;var newStr: PChar): Integer; stdcall; var sTemp: string; begin Result := -1; stemp := ‘Hello‘; newStr := PChar(sTemp); Result := 0; end;
Delphi调用:
procedure TForm1.Button1Click(Sender: TObject); var macdll: THandle; Encry: function(priKey, oldStr: PChar;var newStr: PChar): Integer; stdcall; nvalue: PChar; begin macdll := LoadLibrary(‘test.dll‘); if macdll <> 0 then begin @Encry := GetProcAddress(macdll, ‘TestDll‘); if @Encry <> nil then begin nvalue := ‘‘; Encry(‘test1‘, ‘test2‘, nvalue); ShowMessage(nvalue); end; FreeLibrary(macdll); end; end;
C++调用:char* ¶m2(指针引用)
char * output; typedef int(__stdcall *TestDll)(char* pKey, char* param1, char* ¶m2); TestDll pFun = (TestDll)GetProcAddress(hModule, "TestDll"); if (pFun) { pFun("test1", "test2", output); }
以上是今天所碰到的问题,做个记录,以防忘记。
标签:
原文地址:http://www.cnblogs.com/things/p/5093446.html