编程语言
首页 > 编程语言> > 将com组装成dll,供java调用

将com组装成dll,供java调用

作者:互联网

1,使用ATL生成动态库

参考链接:https://blog.csdn.net/wangwenjing90/article/details/8771934

2,自己手动生成dll动态库,具体的生成方式就不进行赘述,这里只显示代码

2.1 hello.h 文件

#ifndef _HELLO_H_
#define _HELLO_H_

extern "C" __declspec(dllexport) void print_hello();

extern "C" __declspec(dllexport) int myadd(int x,int y);

extern "C" __declspec(dllexport) long mynewadd(long x,long y);

#endif

2.2  hello.cpp

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

#include "atlcomcli.h"
#import "FirstCOM.dll" no_namespace


extern "C" __declspec(dllexport) void print_hello(){
	printf("hello xiao huang ********");
	return;
}

extern "C" __declspec(dllexport) int myadd(int x,int y){
	
	return x+y;
}

extern "C" __declspec(dllexport) long mynewadd(long x,long y){

	CoInitialize(NULL);
	CLSID clsid;
	CLSIDFromProgID(OLESTR("FirstCOM.math.1"),&clsid);
	
	CComPtr<IFirstClass> pFirstClass;//智能指针
	pFirstClass.CoCreateInstance(clsid);
	long ret = pFirstClass->Add(x,y);
	printf("%d\n",ret);
	pFirstClass.Release();
	CoUninitialize();

	return ret;
}

2.3 修改配置为X64,因为本人的电脑为64位,需要注意的是 ATL生成的动态库 FirstCOM.dll 这个动态库,是和.cpp .h一样的目录下,这样可以可找到的。

build 即可生成动态库

3 ,新建java的JNA进行C的开发 程序,使用的是maven 进行依赖包的管理

public class JNATest4 {

    public interface Clibrary extends Library {
        //加载libhello.so链接库
        JNATest4.Clibrary INSTANTCE = (JNATest4.Clibrary) Native.loadLibrary("hello", Clibrary.class);

        //此方法为链接库中的方法
        void print_hello();

        int myadd(int x, int y);

        long mynewadd(long x, long y);
    }

    public static void main(String[] args) {
        //调用
        Clibrary.INSTANTCE.print_hello();
        int res = Clibrary.INSTANTCE.myadd(1, 2);

        long newres = Clibrary.INSTANTCE.mynewadd(5, 6);

        System.out.println(res);
        System.out.println(newres);


    }
}

4 编译即可运行。

标签:__,java,int,declspec,long,dll,Clibrary,com,hello
来源: https://blog.csdn.net/zhanghua1068/article/details/101303427