1. Generating dynamic libraries using ATL
Reference link: https://blog.csdn.net/wangwenjing90/article/details/8771934
2. Generate dll Dynamic Library manually, the specific way of generation will not be elaborated, only the code is shown here.
2.1 hello.h file
#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;//Intelligent pointer pFirstClass.CoCreateInstance(clsid); long ret = pFirstClass->Add(x,y); printf("%d\n",ret); pFirstClass.Release(); CoUninitialize(); return ret; }
2.3 Modify the configuration to X64, because my computer is 64 bits. It should be noted that the dynamic library FirstCOM.dll generated by ATL is in the same directory as. cpp.h, so that it can be found.
build to generate dynamic libraries
3. New java JNA for C development program, using maven for dependency package management
public class JNATest4 { public interface Clibrary extends Library { //Load libhello.so link library JNATest4.Clibrary INSTANTCE = (JNATest4.Clibrary) Native.loadLibrary("hello", Clibrary.class); //This method is the method in the link library void print_hello(); int myadd(int x, int y); long mynewadd(long x, long y); } public static void main(String[] args) { //call 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. Compile and run.