简体   繁体   中英

Run C# code from Java and vice-versa

I have a game server which is made in Java. I want to make a plugin system that loads a .NET DLL and calls events / functions inside that DLL, then inside those I'll have to call functions in the game server (Java). The only part that is giving me trouble at the moment is how to interface java and a .NET dll.

I've been searching and found some things but they were all based on products and I want to make my own interface for that. Ah, not to mention it needs to have high performance, the code will be called a lot of times in a second if it has to. Could someone point or give-me ideas how could I work this out?

EDIT:

To make it more explicit:

  1. Game Server (Java application) calls a function in .NET dll
  2. The .NET function just called by java, calls multiple functions from Game Server (Java Application).

Take a look at jni4net if you're targeting Windows. It's an alpha quality release, but Robocode already uses it to run .NET robots inside the Java runtime.

Another option is to use a high-performance messaging approach. You'll need a second process - likely a .NET plug-in host. That process then exchanges messages with the main Java game process. Messaging libraries like 0MQ are pretty darn fast but may not be fast enough for what you have in mind. In addition, you'll have to create a lot of message plumbing which may be cost/time prohibitive.

Try using iKVM:

IKVM.NET is an implementation of Java for Mono and the Microsoft .NET Framework. It includes the following components:

  • A Java Virtual Machine implemented in .NET
  • A .NET implementation of the Java class libraries Tools that enable Java and .NET interoperability

http://www.ikvm.net/

If you only have a few methods you are calling you might just use JNI and do it yourself instead of a 3rd Party tool (though I admit I don't know the details of jni4net). Just a word of caution, the project I'm on had to do a similar thing (C# -> C/C++ -> Java via JNI) and we had nothing but problems with it. Problems mainly because the java api didn't have any good documentation so that might have been part of it. If at all possible try to keep it to one language but if that is not possible, make sure you do lots of error checking. When the app crashes, it is very hard to find the problem (unless you own both the java and C# sutff). Just my $0.02...

Avoid binary coupling. Write your own interop layer based on the architectural approach in this article. http://www.codeproject.com/KB/architecture/SerInterfaceXXsd2Code.aspx . For high performance you can replace also the XML serialization mentioned in this article with hessian.

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