显示调用c++动态链接库


1.动态链接库生成

<span style="background-color: rgb(255, 255, 255);">//operator.h

#ifndef OPERATOR_H
#define OPERATOR_H

#include <stdio.h>
#include <stdlib.h>

#ifdef __cplusplus
extern "C"
{
#endif
int Add(int a, int b);
int Sub(int a, int b);

#ifdef __cplusplus
}
#endif
#endif</span>
<span style="background-color: rgb(255, 255, 255);">
</span>
<pre name="code" class="html"><span style="background-color: rgb(255, 255, 255);">//operator.cpp

#include "operator.h"
int Add(int a, int b)
{
	return a + b;
}

int Sub(int a, int b)
{
	return a - b;
}</span>

<pre name="code" class="html">//operator_dll.h
#ifndef _OPERATOR_DLL_H
#define _OPERATOR_DLL_H


#define DLLEXPORT __declspec(dllexport)

extern "C"  DLLEXPORT int Operator(int a, int b, int *result);

#endif

//operator_dll.cpp
#include "operator_dll.h"
#include "operator.h"

DLLEXPORT int Operator(int a, int b, int *result)
{

	*result = Add(a, b) + Sub(a, b);

	if (result)
	{
		return 1;
	}
	else
	{
	return 0;
	}

}

//test_main

#include "operator_dll.h"
#include <stdio.h>

int main(void)
{
	int a, b, result;
	a= 4;
	b = 3;
    Operator(a, b, &result);
	printf("operator result : %d \n", result);

	return 0;
}

2.动态链接库的调用
 
<pre name="code" class="html">#include <Windows.h>
#include <string>

using namespace std;

typedef int    (*OperatorFunc)(int ,int ,int* );
void test_operator_dll()
{
	int result;
	result = 0;
	OperatorFunc _OperatorFunc;

	HMODULE handle = LoadLibrary("mydll.dll");
	
	if (handle)
	{
		_OperatorFunc = (OperatorFunc)GetProcAddress(handle, "Operator");
		if (_OperatorFunc)
		{
			_OperatorFunc(4, 3, &result);
			printf("result = %d", result);
		}
		else
		{
			printf("GetProcAddress() is failed : %d\n", GetLastError());
		}

		FreeLibrary(handle);
	}
	else
	{
		printf("LoadLibrary() is failed : %d \n", GetLastError());
	}

}

int main(void)
{
	test_operator_dll();
	return 1;
}

3.运行结果:
 
result = 8



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值