博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在使用C++ Builder的调用VC的DLL的时候遇到了'Access violation at address xxx'的错误,以下是测试程序:

 

C++ Builder代码:

//---------------------------------------------------------------------------

#include <stdio.h>
#include <windows.h>

#pragma hdrstop

//---------------------------------------------------------------------------
int __stdcall (*add)(int, int);
int __stdcall (*sub)(int, int);

#pragma argsused
int main(int argc, char* argv[])
{
        HMODULE handle = LoadLibrary("AddFunc.dll");
        add = GetProcAddress(handle, "Add");
        sub = GetProcAddress(handle, "Sub");

        printf("2+3=%d\n", add(2, 3));
        printf("100-30=%d\n", sub(100, 30));

        FreeLibrary(handle);
        getchar();
        return 0;
}
//---------------------------------------------------------------------------
 
 
DLL代码:
.h:
// The following ifdef block is the standard way of creating macros which make exporting 
// from a DLL simpler. All files within this DLL are compiled with the ADDFUNC_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see 
// ADDFUNC_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef ADDFUNC_EXPORTS
#define ADDFUNC_API extern "C" __declspec(dllexport)
#else
#define ADDFUNC_API extern "C" __declspec(dllimport)
#endif


ADDFUNC_API int Add(int a, int b);

ADDFUNC_API int Sub(int a, int b);

 

.c:

// AddFunc.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "AddFunc.h"


ADDFUNC_API int Add(int a, int b)
{
	return (a + b);
}

ADDFUNC_API int Sub(int a, int b)
{
	return (a - b);
}
 

于是调用就出现了该异常,经过查阅资料得知VC的DLL在export的时候要加上__stdcall的修饰,强制使用WINAPI的导出方式,对两个函数修改为(.h, .c):

ADDFUNC_API int __stdcall Add(int a, int b);

ADDFUNC_API int __stdcall Sub(int a, int b);

 

结果发现导出的函数发生了变化_Add@4, __Sub@4,解决方法是在VC工程中加入一个AddFunc.def,内容如下:

LIBRARY	"AddFunc"

EXPORTS
Add @ 1
Sub @ 2

 

至此,解决问题。



作者:Harry Huang
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.