在Java程序中调用C#方法

Has*_*imR 14 c# c++ java java-native-interface wrapper

由于不同的原因,无法使用JNI直接在Java中调用C#方法.首先,我们必须使用C++为C#编写一个包装器,然后创建dll并通过Java中的JNI使用它.

我在C++中调用C#代码时遇到问题.我正在将C#.netmodule文件添加到C++项目中.代码粘贴在下面.如果我做错了,请指导我.

这是我的托管C++类UsbSerialNum.h:

#using <mscorlib.dll>
#include <iostream>
#using "UsbSerialNumberCSharp.netmodule"

using namespace std;

using namespace System;

public __gc class UsbSerialNum
{
    public:

        UsbSerialNumberCSharp::UsbSerialNumberCSharp __gc *t;

        UsbSerialNum() {
            cout<<"Hello from C++";
            t = new UsbSerialNumberCSharp::UsbSerialNumberCSharp();
        }

        void CallUsbSerialNumberCSharpHello() {
            t->hello();
        }
};
Run Code Online (Sandbox Code Playgroud)

UsbSerialNumberCSharp.cs我创建.netmodule文件的C#文件:

using System.Collections.Generic;
using System.Text;

namespace UsbSerialNumberCSharp
{
    public class UsbSerialNumberCSharp
    {

        public UsbSerialNumberCSharp(){
            Console.WriteLine("hello");
        }

        public static void hello()
        {
            Console.WriteLine("hello");
        }

        public void helloCSharp ()
        {
            Console.WriteLine("helloCSharp");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我创建的主makeDLL.cpp文件makeDLL.dll:

#include "jni.h"
#include <iostream>


// This is the java header created using the javah -jni command.
#include "testDLL.h"


// This is the Managed C++ header that contains the call to the C#
#include "UsbSerialNum.h"

using namespace std;


JNIEXPORT void JNICALL Java_testDLL_hello
(JNIEnv *, jobject) {

    // Instantiate the MC++ class.
    UsbSerialNum* serial = new UsbSerialNum();
    serial->CallUsbSerialNumberCSharpHello();
}
Run Code Online (Sandbox Code Playgroud)

这是我的java类:

public class testDLL {

    static {
        System.loadLibrary("makeDLL");
    }

    /**
     * @param args
     */
    public static void main (String[] args) {
        //        new testDLL().GetUSBDevices("SCR3", 100);
        new testDLL().hello();
    }

    public native void hello();

}
Run Code Online (Sandbox Code Playgroud)

编辑:

如果我在主文件中忽略对UsbSerial.h的调用,即使用简单的C++,那么我的代码在Java中运行良好.基本上C++托管类不能正常工作.请指导我.谢谢.

Vir*_*zzo 7

了解完全需要这种互操作性的内容会很有用.无论如何,你应该研究一下IKVM ; 或者,您可以(如同类似问题的建议)使用COM作为桥接:将C#/ CLR公开为COM接口,然后在Java中使用com4j.