• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling C main() from Java  RSS feed

 
Edward Mclogan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings Geeks !
I know I can call a function in C from java using JNI. However, I need to interact with a C program has ALL the relevant code in the main() method.
Any help on how this can be accomplished is highly appreciated.
Thanks,
Edward
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried calling main() like you do any other function? I'm unfamiliar with JNI, but it seems logical that this would work. If you have access to the C source code, you could simply re-arrange it so that the code is in a different function.
Of course, you've probably already thought of this. If so, I'm sorry that I can't be of any more help at the moment. These are the only ideas I can think of for now. Hopefully someone else will have something more useful to add.
Layne
 
Edward Mclogan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Layne,
Thanks for your message. Since I have a very large number of C programs creating new funtions might turn out to be a tedious task. Ideally, I would like to find a way to call the C program directly.
However, your suggestion is much appreciated and this is the path that I'll follow if I cannot find a less intrusive solution.
Thanks,
Edward
 
Loren Rosen
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this will work, though you'll have to check the C program for how it uses the command line, stdin, etc. and adjust for that. If performance isn't critical it would be a lot easier to just run the program in a separate process via Runtime.exec().
 
Malcolm Featonby
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Edward,
How about writing a small piece of wrapper code in C which is "JNI aware" as it were. This C wrapper function could then call the main() method you are after. Likewise you could write a simple Java class that wraps the call to this and thereby have a simple interface for your java code and no changes required to your C code.
Once this is working I am sure you could get clever with it and have the name of the module containing the main() method passed in from the Java wrapper class thereby allowing you to call main() in pretty much anything.
Hope this helps.
Malcolm
 
Malcolm Featonby
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry - - my first response won't help you unless you can relink the C module as a DLL. Even then I think you are going to have to move the processing you require into another function.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!