java c# 调用,在Java程序中调用C#方法

C# methods cannot be called directly in Java using JNI due to different reasons. So first we have to write a wrapper for C# using C++ then create the dll and use it through JNI in Java.

I have problem in calling C# code in C++. I'm adding C# .netmodule file to a C++ project. Code is pasted below. Please guide me if i'm doing anything wrong.

This is my managed C++ class UsbSerialNum.h:

#using

#include

#using "UsbSerialNumberCSharp.netmodule"

using namespace std;

using namespace System;

public __gc class UsbSerialNum

{

public:

UsbSerialNumberCSharp::UsbSerialNumberCSharp __gc *t;

UsbSerialNum() {

cout<

t = new UsbSerialNumberCSharp::UsbSerialNumberCSharp();

}

void CallUsbSerialNumberCSharpHello() {

t->hello();

}

};

C# UsbSerialNumberCSharp.cs file from which i've created the .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");

}

}

}

Here is my main makeDLL.cpp file from which makeDLL.dll is created:

#include "jni.h"

#include

// 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();

}

Here is my java class:

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:

If i simply ignore the call to UsbSerial.h in my main file i.e. use simple C++ then my code is working fine in Java. Basically C++ managed class is not working properly.

Please guide me. Thanks.

解决方案

It would be useful to know what you need this interoperability for exactly. In any case, you should look into IKVM; alternatively you can (as has been suggested for a similar problem) use COM as a bridge: expose the C#/CLR as a COM interface and then use com4j in Java.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值