在Java程序中调用C#方法

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

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

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

 #using  #include  #using "UsbSerialNumberCSharp.netmodule" using namespace std; using namespace System; public __gc class UsbSerialNum { public: UsbSerialNumberCSharp::UsbSerialNumberCSharp __gc *t; UsbSerialNum() { cout<hello(); } }; 

C# UsbSerialNumberCSharp.cs文件,我从中创建了.netmodule文件:

 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"); } } } 

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

 #include "jni.h" #include  // 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(); } 

这是我的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(); } 

编辑:

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

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

您可以避免使用C#,但仍然只能使用C ++查询WMI。 请参阅使用WMI调用对象上的方法