在Delphi中动态调用C++的DLL

来源:互联网 发布:vb调用matlab 编辑:程序博客网 时间:2024/05/16 09:23

/*--------------------------*/

VC中的.H代码:

/*--------------------------*/

#ifndef CFUN_H
#define CFUN_H

extern "C" __declspec(dllexport) int add(int a, int b);

#endif

 

/*--------------------------*/

VC中的CPP代码:

/*--------------------------*/

 

// cfun.cpp : 定义 DLL 应用程序的入口点。
//

#include "stdafx.h"


#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    return TRUE;
}

extern "C" __declspec(dllexport) int add(int a, int b)
{
    return a + b;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

/*--------------------------*/

Delphi中的代码:

/*--------------------------*/

type
    Tadd = function(num1:Integer; num2:Integer):Integer; cdecl;

procedure TForm1.btn1Click(Sender: TObject);
var
    handle:THandle;
    FPointer:TFarProc;
    MyFunc:Tadd;
    i:Integer;
begin
    handle := LoadLibrary('cfun.dll');

    if (handle<> 0) then
    try
        FPointer := GetProcAddress(handle, 'add');
        if FPointer <> nil then
        begin
            MyFunc := Tadd(FPointer);
            i := MyFunc(10,20);

            edt1.Text := IntToStr(i);

        end;

        finally
            FreeLibrary(handle);
        end
    else
      ShowMessage('未找到动态链接库cfun.dll');




end;

 

原创粉丝点击