开发者

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 (e.g. 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 开发者_JAVA技巧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.


You might be interested in trying to convert your Java bytecode code in .NET CIL with IKVM.NET.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜