天天看點

.net core 調用c dll_C/C++調用delphi編寫的dll檔案

.net core 調用c dll_C/C++調用delphi編寫的dll檔案

C/C++調用delphi編寫的dll檔案

1. delphi 編寫的dll檔案源碼

library xrBitOperation;

{ Important note about DLL memory management: ShareMem must be the
  first unit in your library's USES clause AND your project's (select
  Project-View Source) USES clause if your DLL exports any procedures or
  functions that pass strings as parameters or function results. This
  applies to all strings passed to and from your DLL--even those that
  are nested in records and classes. ShareMem is the interface unit to
  the BORLNDMM.DLL shared memory manager, which must be deployed along
  with your DLL. To avoid using BORLNDMM.DLL, pass string information
  using PChar or ShortString parameters. }

uses
  System.SysUtils,
  System.Classes;


function xrbittest(B:Byte;N:Byte):Boolean;stdcall;
begin
  result := ((B shr N) and $01) = $01;
end;

function xrBitset(B:Byte;N:Byte): Byte;stdcall;
begin
  result := B or (1 shl N);
end;

function xrBitClear(B:Byte;N:Byte):Byte;stdcall;
begin
  result := B and (not(1 shl N));
end;


{$R *.res}

//注意Exports的位置
exports
  xrbittest index 1 name 'xrbittest',
  xrbitset index 2 name 'xrbitset',
  xrbitclear index 3 name 'xrbitclear';

//如果用下面的格式,在dll檔案的編譯時不會出錯,但是在使用時會出錯
//xrbittest,xrbitset,xrbitclear;

begin
end.
           

2. C語言調用

#include "stdio.h"
#include "stdlib.h"
#include "windows.h"

typedef  unsigned char (_stdcall *xrbittest)(unsigned char, unsigned char);

int main(void)
{
	unsigned char B;
	unsigned char B0,B1;
	HMODULE h = LoadLibraryA("xrBitOPeration.dll");
	if (h == NULL)
	{
		printf("xrBitOPeration.dll NOT found!.n");
	}
	else
	{
		printf("Load Library Success!.n");
	}

	xrbittest proc = (xrbittest)GetProcAddress(h, "xrbittest");
	if (proc == NULL)
	{
		printf("function:xrbittest Not found.n");
	}
	else
	{
		printf("function:xrbittest Found.n");
	}

	B = 1;
	B0 = proc(B, 0);
	printf("B0 = %d.", B0);

	B1 = proc(B, 1);
	printf("B1 = %d.", B1);

	getchar();
	return 0;

}
           

繼續閱讀