• c++ c# java 调用 c++ 写的dll


    1. vs 中新建win32 dll 项目   testdll

    添加实现文件       test.cpp

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    int Add(int plus1, int plus2)
    {
    int add_result = plus1 + plus2;
    return add_result;
    }

    添加模板定义文件

    LIBRARY "testdll"
    EXPORTS
    Add @1

    编译生成 dll 文件

    2.  c++  程序调用  c++ dll

    新建 c++控制台 程序

    copy 第一步 生成的 lib 文件 到 工程目录下

    添加引用 dll 的 头文件  main.h

    pragma comment(lib,"testdll.lib")
    extern "C"_declspec(dllimport) int Add(int a, int b);

     主文件

    #include "stdafx.h"
    #include <iostream>
    #include "main.h"
    using namespace std;
    int _tmain(int argc, _TCHAR* argv[])
    {
    cout << "aaa" << endl;
    cout << Add(3,4)<< endl;
    return 0;
    }

     编译 生成 exe 文件,运行时确保第一步生成的dll 在 exe 同目录下,或者在windows目录或者在 环境变量path指定的目录

    3. c# 程序调用 c++ dll

       新建 winform 或者控制台程序

    添加  代码到 任意类中

    [DllImport("testdll.dll", EntryPoint = "Add")]
    private extern static int Add(int I_A, int I_B);

    在winform中的调用方式:

       MessageBox.Show(Add(3, 4).ToString());

    编译 生成 exe 文件,运行时确保第一步生成的dll 在 exe 同目录下,或者在windows目录或者在 环境变量path指定的目录

    4. java 调用 c++ 写的 dll

    新建 java 控制台程序

    添加  java文件   TestDLL.java, 声明需要引用的方法

    package helloworld;

    public class TestDLL
    {
    static
    {
    System.loadLibrary("javadll");
    }
    public native int add(int num1, int num2);
    }

    在此工程的 bin 目录 下 根据 声明的 java 文件 生成对应的 .h 头文件

    通过javah 命令

    javah -classpath . -jni helloworld.TestDLL   此时会生成  helloworld_TestDLL.h  文件 

    新建 c++ 的 dll 项目,将 helloworld_TestDLL.h  添加 到 项目中

    将 jniport.h 文件添加到 项目中,  如果在本地找不到,可以在网上下载此文件

    添加 实现文件 testDll.cpp

    #include "stdafx.h"

    #include "helloworld_TestDLL.h"



    JNIEXPORT jint JNICALL Java_helloworld_TestDLL_add

    (JNIEnv * env, jobject obj, jint num1, jint num2)

    {

    return num1 + num2;

    }

    生成dll,将此dll copy 到  java项目中的lib 文件中

    在java 项目的 main 方法中调用  dll中的方法

    public static void main(String[] args) {
      

    System.out.println(new TestDLL().add(3,4));

    }

    运行时 ,将 dll文件copy 到jdk 的bin目录下

  • 相关阅读:
    MS面试归来:)
    准备出发到成都
    线程的同步机制(zz)
    Windows Vista(zz)
    这几天上海热晕了
    微软官方:Vista硬件要求指南(zz)
    有趣的递归缩写(Recursive acronym)
    《三国志》生僻人名读法集(zz)
    Git bash常用命令
    各大输入法分类词库内部格式的简单比较
  • 原文地址:https://www.cnblogs.com/xl711436/p/3731763.html
Copyright © 2020-2023  润新知