Phương thức C# không thể được gọi trực tiếp trong Java bằng JNI do các lý do khác nhau. Vì vậy, đầu tiên chúng ta phải viết một wrapper cho C# bằng cách sử dụng C++ sau đó tạo dll và sử dụng nó thông qua JNI trong Java.Gọi phương thức C# trong một chương trình Java
Tôi gặp sự cố khi gọi mã C# bằng C++. Tôi đang thêm tập tin C# .netmodule
vào một dự án C++. Mã được dán bên dưới. Vui lòng hướng dẫn tôi nếu tôi làm gì sai.
này được C quản lý của tôi ++ lớp 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
tập tin từ mà tôi đã tạo .netmodule
file:
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");
}
}
}
Dưới đây là chính makeDLL.cpp
tập tin của tôi từ đó makeDLL.dll
được tạo ra :
#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();
}
Đây là lớp học java của tôi:
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();
}
EDIT:
Nếu tôi chỉ đơn giản là bỏ qua các cuộc gọi đến UsbSerial.h trong tập tin chính của tôi ví dụ: sử dụng đơn giản, C++ sau đó mã của tôi đang làm việc tốt trong Java. Về cơ bản C + + quản lý lớp học không hoạt động đúng. Vui lòng hướng dẫn tôi. Cảm ơn.
vào thời điểm nào bạn gặp lỗi? – Illuminati
Có vấn đề gì? Đây có phải là C++ được quản lý không? Tôi không nhận ra các bit '__gc' – flipchart
tôi đã chỉnh sửa câu hỏi. làm ơn hãy kiểm tra nó. cảm ơn. – HashimR