[英]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 ++托管類不能正常工作。 請指導我。 謝謝。
您可以避免使用C#,但仍然只能使用C ++查詢WMI。 請參閱使用WMI調用對象上的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.