簡體   English   中英

在Java程序中調用C#方法

[英]Calling C# method within a Java program

由於不同的原因,無法使用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();
        }
};

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 <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 ++托管類不能正常工作。 請指導我。 謝謝。

了解完全需要這種互操作性的內容會很有用。 無論如何,你應該研究一下IKVM ; 或者,您可以(如同類似問題的建議)使用COM作為橋接:將C#/ CLR公開為COM接口,然后在Java中使用com4j

您可以避免使用C#,但仍然只能使用C ++查詢WMI。 請參閱使用WMI調用對象上的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM