代码备份,仅供参考
自述文件
# CSharpCallJava
C# invoke Java via C++ as a wraper.
C# invoke C++ via P/invoke. C++ starts a JVM to run the Java code.
C# code should be compiled in .NET core 2.0
You should edit the Makefile to set the Path of Java SDK
export LD_LIBRARY_PATH=/usr/lib/jvm/java-1.9.0-openjdk-amd64/lib/amd64/server
or add it into your enviroment
# Compile:
javac MyTest.java
make
dotnet build
cscalljava.csproj
Exe
netcoreapp2.0
init.cs
using System;
using System.Runtime.InteropServices;
namespace invoke
{
class Program
{
[DllImport("libc.so.6")]
private static extern int getpid();
// You should edit the path of you .so lib
[DllImport("./wraper.so",EntryPoint="Invokejava")]
private static extern int Invokejava(string message);
static void Main(string[] args)
{
int pid= getpid();
Console.WriteLine(pid);
Console.WriteLine("Hello World!");
int status= Invokejava("Hi C# to cpp");
Console.WriteLine(status);
}
}
}
Makefile
wraper.so:wraper.cpp
g++ -shared -o wraper.so -L/usr/lib/jvm/java-1.9.0-openjdk-amd64/lib/amd64/server -I/usr/lib/jvm/java-9-openjdk-amd64/include -I/usr/lib/jvm/java-9-openjdk-amd64/include/linux/ ./wraper.cpp -fPIC -ljvm
export LD_LIBRARY_PATH=/usr/lib/jvm/java-1.9.0-openjdk-amd64/lib/amd64/server
MyTest.java
public class MyTest {
private static int magic_counter=777;
public static void sayHi() { //
wrapper.cpp
#include
#include
#include
using namespace std;
extern "C"{
int Invokejava(const char* message)
{
JavaVM *jvm; // Pointer to the JVM (Java Virtual Machine)
JNIEnv *env; // Pointer to native interface
//================== prepare loading of Java VM ============================
JavaVMInitArgs vm_args; // Initialization arguments
JavaVMOption* options = new JavaVMOption[1]; // JVM invocation options
options[0].optionString = "-Djava.class.path=."; // where to find java .class
vm_args.version = JNI_VERSION_1_6; // minimum Java version
vm_args.nOptions = 1; // number of options
vm_args.options = options;
服务器托管网 vm_args.ignoreUnrecognized = false; // invalid options make the JVM init fail
//=============== load and initialize Java VM and JNI interface =============
jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); // YES !!
delete options; // we then no longer need the initialisation options.
if (rc != JNI_OK) {
// TO DO: error processing...
cin.get();
exit(EXIT_FAILURE);
}
//=============== Display JVM version =======================================
cout GetVersion();
cout >16)&0x0f) FindClass("MyTest");
if(cls2== nullptr){
cerrGetStaticMethodID(cls2,"sayHi","()V");
if(mid==nullptr)
cerrCallStaticVoidMethod(cls2,mid);
}
}
jmethodID mid2 = env->GetStaticMethodID(cls2,"Square","(I)I");
if(mid2==nullptr){
服务器托管网 cerr>i;
coutCallStaticIntMethod(cls2,mid2,(jint)i);
coutDestroyJavaVM();
cin.get();
return 0;
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
RDP(远程桌面协议)是一种用于远程访问和控制计算机的协议。RDP协议最早由微软开发,并于1998年首次引入Windows NT 4.0操作系统中。随后,RDP在Windows 2000、Windows XP、Windows Server等操作系统中得到了进一…