java调用c# dll

rt,碰到个奇怪的需求,需要用Java调用.net的dll。各种search,解决方案倒是不少,JNI,JNA,Jni4net,Javonet,Jacob…
其中jni和jna使用起来比较简单,但是都是针对c/c++的dll,如果要调c#的dll的话,据说要写一层c++的桥接,也就是说Java调c++,c++再调c#,艾玛,反正我试了下没成功- -
Jni4net我也是看了看,说实话,没看懂- -
Javonet要收费,免费试用30天,所以,你懂得- -
那么只剩Jacob了,这也是我唯一试成功的一个,官网:http://danadler.com/jacob/

步骤如下:
1,在官网上把需要的包下下来,其文件目录如下:
这里写图片描述
将jacob-1.18-x64.dll拷贝到C:\Windows\System32下(我是win7 64位)

2,制作强签名key,开始菜单中点击如下目录,打开Visual Studio Command Prompt(选择正确的版本哦):
这里写图片描述
敲入如下命令生成强命名key:
sn -k MyKeyFire.snk
其中MyKeyFire是名字,可以自己随便取。
在当前目录(System32)中找到该文件,任意复制到一个新文件夹。
sn.exe介绍请移步https://msdn.microsoft.com/zh-cn/library/k5b5tt23(VS.80).aspx

3,C#程序
vs2013新建类库输出项目TestCom:
这里写图片描述

Class1.cs中写入代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestCom
{
    public interface IHelloWorld
    {
        string say(string s);
    }

    public class HelloWorld :IHelloWorld
    {
        public HelloWorld() { }

        public string say(string s)
        {
            return "test " + s;
        }
    }
}

右击项目名,选择属性:
1)应用程序–>程序集信息,勾选使程序集COM可见
2)生成–>勾选为COM互操作注册
3)签名–>勾选为程序集签名,选择刚刚生成的强签名文件

编译程序,在debug目录下会生成 TestCom.dll 和TestCom.tlb

4,回到Visual Studio Command Prompt,进入Debug目录,运行注册命令:
regasm TestCom.DLL /tlb:TestCom.tlb
gacutil -i TestCom.DLL (执行这个命令需要TestCom.DLL 具有强名称)
这里写图片描述

5,Java程序
新建一个java项目,将jacob.jar包add build path,
main程序如下:

public static void main(String[] args)
{
    try{  
        ActiveXComponent dotnetCom =new ActiveXComponent("TestCom.HelloWorld");
        Variant var = Dispatch.call(dotnetCom,"say","hello world");
        String str  = var.toString(); 
        System.out.println(str);
    } catch (Exception ex) {
         ex.printStackTrace();
    }      
}

运行结果如下:
这里写图片描述

流程总结:
将C# dll注册到注册表中去,从而给java调用

错误分析:
“Can’t co-create object” 方法名写的不对
“Can’t get object clsid from progid” regasm注册有问题

猜你喜欢

转载自blog.csdn.net/leebin_20/article/details/52356065