简体   繁体   中英

Call my own Java code from C#

Having my own Java code I'm using C# to call some unmanaged code that call (via JNI) the java code. I'm using JNI since I need to ensure:

  • the ability that the Java code will run over real JVM and not over some .NET VM
  • the ability to attach to the VM for debugging (IKVM does'nt support it)
  • I need free solution
  • The current free solutions are not applicable (eg IKVM)

Anyway, my question is how can I manage strings passed between these layers in the best manner without leaks. I'm doing something like:

[DllImport(@"MyDll.dll")]
public extern static void receive_message(string receDest, StringBuilder response);

This means I'm allocating the memory for the response in the managed code. I want to avoid that since I don't know in advance the response length. How can I write a JNI appropriate method that will allocate the right buffer for the managed code without leaks. The JNI code should be thread safe.

Any suggestions?

Thanks,

Guy

You may need JNI, but your requirements don't really indicate it.

The requirement to use a real JVM does not dictate the use of JNI. I'd suggest sharpening your requirements, or considering looser coupling. For example, socket comms, web services, a shared database, a shared file, or a queue .

If you really need Java and .NET to be run in the same process, with tight coupling, consider JNBridge .
They've solved the problem you are confronting.

您可能有兴趣尝试使用IKVM.NET在.NET CIL中转换Java字节码代码。

You essentially need to make a remote call into the java program from your .NET-code.

With your current skillset I would suggest that you create a web service in the Java machine - this is relatively easy in Java 6 - and based on the WSDL create a client in your .NET program.

This is probably the cleanest solution with todays technologies.

If that for some reason isn't good enough, then add to your question.

Guy -- Regarding Cheeso's response, and your respones to it:

  • JNBridgePro does allow the JVM to be started automatically and run inside the .NET process (in addition to the option of starting it explicitly). See the "shared-memory" communications mechanism discussed in the documentation.

  • JNBridgePro does allow you to attach a Java debugger, even when the JVM is running inside the .NET process. Contact support@jnbridge.com for details, as well as for details on configuring the JVM.

  • Can't do much about it not being free, but it might be worth your while to check it out anyway.

Disclosure: Yes, I am with JNBridge.

I think you could use jni4net as a bridge library. Or you could just look at source code and grab some ideas (LGPL/GPL).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM