显示调用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
 
 
 
 
 

你可能感兴趣的:(C++,C语言)