csharp to java JNI porting call to run on ubuntu

2019-09-20 01:28发布

问题:

I getting bug: crash happened outside the Java Virtual Machine in native code. whenever i run with class file with native library and .net module file it works fine. but when i try to run alone class file and native library it gets crash .please clarify my mistake i have done, please review my code. for your reference with parameter

==========================================

 public class Sum
    {
        public int add(int a, int b)
        {
            return a + b;
        }
    }

===========================================

save as Sum.cs and compile it to module using cmd:

csc /t:module sum.cs

Create Java File to test

===========================================

public class test{
public native int add(int a,int b);
 static {
        System.loadLibrary("JSample");
    }

    public static void main (String[] args) {
       System.out.println(new test().add(10,15));
    }
}

==========================================

save it as test.java compile as

javac test.java

create native header file

javah -jni test

it will create test.h

create win32 project using visual studio (I used VS2010) Choose project name as JSample

include header and C#.net module write header for manged C++ conversion

==============================================

#using <mscorlib.dll>
#using "Sum.netmodule"
using namespace System;
public __gc class SumC
{
public:
    Sum __gc *t;
    SumC()
    {
        t = new Sum();          
    }
    int callCSharpSum(int a,int b)
    {
        return  t->add(a,b);
    }
};

===========================================

save it as sum.h

create sum.cpp file

============================================

#include <jni.h>
#include "test.h"
#include "sum.h"

JNIEXPORT jint JNICALL Java_test_add
    (JNIEnv *, jobject, jint a, jint b)
{
    SumC* t = new SumC();  
    return t->callCSharpSum(a ,b );
}

=============================================

optimize compiler to build /clr:oldSyntax Include Jdk/Include directory path build the project. we will Get JSample DLL

run the project with C#.net module,Native DLL file and class file at the same folder.

java test

25

but whenever i run the code with dll file and class file alone. it shows bug report The crash happened outside the Java Virtual Machine in native code. please clarify how to port managed code C# into C++ (Win32 Un-Managed code). library file.

回答1:

To use .NET assemblies from Java, I strongly suggest you look at IKVM, which is a Java VM that bridges to .NET Runtime.

I've used this back in (I think) 2004 for production software and it worked nicely. The project is actively maintained and recieves support for .NET 4 and Java 7 these days.

You have a choice of

  • running the Java code in IKVM so you can use .NET libraries
  • run a .NET program that loads java libraries (e.g. jars)

Both ways, there is a preprocessing step to translate the jars to DLLS or viceversa.

See http://ikvm.net