Has*_*imR 14 c# c++ java java-native-interface wrapper
由于不同的原因,无法使用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();
}
};
Run Code Online (Sandbox Code Playgroud)
UsbSerialNumberCSharp.cs我创建.netmodule文件的C#文件:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我创建的主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();
}
Run Code Online (Sandbox Code Playgroud)
这是我的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();
}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果我在主文件中忽略对UsbSerial.h的调用,即使用简单的C++,那么我的代码在Java中运行良好.基本上C++托管类不能正常工作.请指导我.谢谢.
| 归档时间: |
|
| 查看次数: |
4887 次 |
| 最近记录: |