2011-11-18 131 views
14

由於不同的原因,不能使用JNI直接在Java中調用C#方法。所以首先,我們必須使用C++爲C#編寫包裝器,然後創建dll並通過Java中的JNI使用它。在Java程序中調用C#方法

我在調用C++中的C#代碼時遇到了問題。我將C#.netmodule文件添加到C++項目中。代碼粘貼在下面。如果我做錯了任何事,請指導我。

這是我的託管C++類UsbSerialNum.h:從我創建了.netmodule文件

#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(); 
     } 
}; 

C#UsbSerialNumberCSharp.cs文件:

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.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(); 
} 

這裏是我的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++託管類不能正常工作。 請指導我。謝謝。

+0

在哪一點您會收到錯誤? – Illuminati

+0

問題是什麼?這是託管的C++嗎?我不認識我編輯過這個問題的'__gc'位 – flipchart

+0

。請檢查一下。謝謝。 – HashimR

回答

7

確切地知道您需要這種互操作性會很有用。無論如何,你應該看看IKVM;或者,您可以(如同建議的類似問題一樣)使用COM作爲橋接:將C#/ CLR作爲COM接口公開,然後在Java中使用com4j

+0

我想獲得所有連接的USB的序列號,已經用C#編寫代碼,想要在Java中使用它。 – HashimR