Java app calling a Delphi DLL

Hello

I have a Java application that must call functions inside a large D7 dll.
For that, I used JNI calls. That part is OK and the delphi dll is receiving
the function parameters smoothly.

The Delphi dll has a couple Forms in it. And these Forms are unresponsive.
Timers don't work. Buttons will not invoke OnClick handlers.
Most important,  the assync sockets in the forms, which the
dll uses to deliver its work, are not functioning either.

It seems that the dll is not receiving Windows messages.
I tried to simulate the application loop, but failed.
The same DLL works fine if called from  Delphi or even
a .NET C# application.

Anyone knows what can be done to make this work?
Any help will be appreciated...

Omar
0
Omar
10/27/2010 11:10:13 AM
embarcadero.delphi.nativeapi 1236 articles. 1 followers. Follow

5 Replies
1250 Views

Similar Articles

[PageSpeed] 51

After some research, I found that if I used Form.ShowModal
instead of Form.Show, the DLL worked better.

Of course ShowModal blocks the thread, so I it must be called 
from an independent Java thread, which remains blocked in
the modal call forever. 

The DLL function calls come from another thread.
So the shared variables in the DLL must be guarded by crititical sections.

Another tip: 
set IsMultithread := true in the DLL.
This instructs memory allocation to work in a thread safe way.
0
Omar
10/27/2010 4:07:26 PM
> I have a Java application that must call functions inside a large D7 dll.
> For that, I used JNI calls. That part is OK and the delphi dll is 
> receiving
> the function parameters smoothly.
>
> The Delphi dll has a couple Forms in it. And these Forms are unresponsive.
> Timers don't work. Buttons will not invoke OnClick handlers.
> Most important,  the assync sockets in the forms, which the
> dll uses to deliver its work, are not functioning either.
>
> It seems that the dll is not receiving Windows messages.
> I tried to simulate the application loop, but failed.
> The same DLL works fine if called from  Delphi or even
> a .NET C# application.
>
> Anyone knows what can be done to make this work?

I already had similar behaviour altough my DLL was not called from Java but 
from another esoteric language.
This happend when the calling application has no message pump.
The solution was to put most of the code into a worker thread with his own 
message queue and message pump.

Youi can easily reproduce the situation by writing a simple Delphi test 
application which calls your DLL from a worker thread not having a message 
pump (this is the default for thread created by delphi RTL). You'll see that 
your DLL is not receiving any message from Windows.

--
francois.piette@overbyte.be
The author of the freeware multi-tier middleware MidWare
The author of the freeware Internet Component Suite (ICS)
http://www.overbyte.be
0
Francois
10/28/2010 7:20:10 AM
When a JNI function call creates a Form and returns, it seems
that the actual Window is destroyed (or garbage collected).
You can still call form methods. For example 
Label1.Text:='test';  Label1.Update;

This works, but the form is just a shadow.
The Windows message loop is no longer in place
when the call returns.

Still, the ShowModal method works :)
Some code:

{code}

vclFormThread.java: --------------------------------------------------------

public class vclFormThread extends Thread {
    
        public MyJNIinterface mji;

        public vclFormThread() {
            super("vclThread");
            System.loadLibrary("MyDelphiDLL"); // load delphi dll
            mji = new MyJNIinterface();        
        }

        public void run() {  
            while (true) { 
                mji.runDelphiForms(); // open modal.. this hangs the thread...
            }
        }

MyJNIinterface.java: --------------------------------------------------------		
		
package MyJNI;

public class MyJNIinterface  {
    native public boolean runDelphiForms();
    native public boolean callMyFunc(String MyStrParam, double MyDoubleParam);
}

Main.java:  --------------------------------------------------------		

public class Main {

    public static void main(String[] args)  {
       vclFormThread vclThread = new vclFormThread();
       vclThread.start();   
	   boolean b;

       while (true) {
         b = vclThread.mji.callMyFunc("test", 123); 

         try{ Thread.currentThread().sleep(100); }
         catch(InterruptedException ie){
         }

       }
    }
}

MyDelphiDLL.dpr:  --------------------------------------------------------

library MyDelphiDLL; // teste de DLL de interface Java/Delphi

uses
  Forms,
  JNI,
  MyForm in 'MyForm.pas';

function Java_MyJNI_runDelphiForms(PEnv: PJNIEnv; Obj: JObject): JBoolean; stdcall;
begin
  if not Assigned(MyTestForm) then
    MyTestForm:= TMyTestForm.Create(nil); 
  MyTestForm.ShowModal;  
  MyTestForm.Free;
  MyTestForm:=nil;
  Result:=true;
end;

function Java_MyJNI_callMyFunc(PEnv: PJNIEnv; Obj: JObject; Arg1: JString; Arg2: JDouble): JBoolean; stdcall;
var JVM: TJNIEnv; S:String; D:double;
begin
  Result:=Assigned(MyTestForm); 
  if Result then 
    begin
      JVM := TJNIEnv.Create(PEnv);
      S:=  JVM.JStringToString(Arg1); //translate string param
      JVM.Free;
      D:=Arg2;  
      MyTestForm.callMyFunc(S,D);
    end;
end;

exports
  Java_MyJNI_runDelphiForms,
  Java_MyJNI_callMyFunc;
end.

MyForm.pas: --------------------------------------------------------		

unit MyForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms;

type

  TMyTestForm = class(TForm)
    ...
    procedure FormCreate(Sender: TObject);
  private
    cs:TRTLCriticalSection; 
    procedure TestDLLOnException(Sender: TObject; E: Exception);
  public
    procedure callMyFunc(const aString:String; aDouble:double);
  end;

var
  MyTestForm: TMyTestForm=nil;

implementation

{$R *.dfm}

procedure TMyTestForm.FormCreate(Sender: TObject);
begin
  IsMultiThread:=true;     //required for thread safe mem management
  InitializeCriticalSection(cs);  //required to access shared vars
  Application.OnException:=TestDLLOnException; {coloca o monitor como console de exceptions}
end;

procedure TMyTestForm.TestDLLOnException(Sender: TObject; E: Exception); //hook unhandled delphi exceptions
begin  
  Memo1.Lines.Add(e.Message); 
end;

procedure TMyTestForm.Timer1Timer(Sender: TObject);
begin
  EnterCriticalSection(cs);
  try
     .. access shared vars
  finally
    LeaveCriticalSection(cs);
  end;
end;

// callMyFunc is called from another thread and must be protected with critical section
procedure TMyTestForm.callMyFunc(const aString:String; aDouble:double);
begin
  EnterCriticalSection(cs);
  try
    .. access shared vars 
  finally
    LeaveCriticalSection(cs);
  end;
end;

end.

{code}

Edited by: Omar Reis on Oct 28, 2010 4:03 AM
0
Omar
10/28/2010 11:06:09 AM
> When a JNI function call creates a Form and returns, it seems
> that the actual Window is destroyed (or garbage collected).

Not sure what you are trying to tell me. You mean JNI call Delphi code in a 
DLL which create a Delphi form ?

> You can still call form methods. For example
> Label1.Text:='test';  Label1.Update;
>
> This works, but the form is just a shadow.
> The Windows message loop is no longer in place
> when the call returns.

Probably the Java application has no message pump, at least not in the 
thread which calls your Delphi code.
If you call Show (TForm.Show), this don't do much except making the window 
visible. For the window to work (that is paint itself and have the GUI 
operating), the message pump in the thrad which created the window /must/ be 
operating.

> Still, the ShowModal method works :)

Yes, ShowModal calls the message pump. So during show modal you have a 
working message pump.
The solution I gave you in my previous message will work. Just try it !

> Some code:

In your function Java_MyJNI_runDelphiForms, if you call Show instead of 
ShowModal, it can't work since you call free imediately after. It looks like 
you have not figured that Show don't do much, it is a kind of asynchonous 
function merely intruction the form to show ITSELF and then return. For the 
form to show itself, it needs a message pump.

--
francois.piette@overbyte.be
The author of the freeware multi-tier middleware MidWare
The author of the freeware Internet Component Suite (ICS)
http://www.overbyte.be
0
Francois
10/28/2010 7:20:39 PM
+> In your function Java_MyJNI_runDelphiForms, if you call Show instead of+
+ShowModal, it can't work since you call free imediately after.+

In the first tests, I created the Form and did not call Form.Free. 
But the Window was destroyed anyway when the JNI function returned.
I was not able to use it in subsequent JNI calls.

This was the only way I found to keep the form running
and call it many times.
0
Omar
10/29/2010 10:45:43 AM
Reply:

Similar Artilces:

Calling Delphi 6 DLL from Delphi 2010
We have a Delphi 6 dll that has a PChar passed to it. The dll function then does a search and returns a PCHar. This works good using Delphi 6 to call and recieve the dll result. We have upgraded our calling program to Delphi 2010 and most of the time, the value is passed back just fine. However, we do have times when we get an access violation, when calling the dll. The dll does process the request. Below is the code. Has anyone had a similar issue using an older version Delphi Dll with Delphi 2010? I am sure that Unicode has something to do with it, but not sure how to fix th...

calling a c++ dll from a delphi vcl app crashes the app upon exit [Edit]
I am using RAD Studio 2010 and I downloaded the latest updates. Since I can't see how I can attach a file to the message, I included in this message the source code for each file: To reproduce this problem follow these steps: Create a project group with two projects, one c++ dll project and one a Delphi VCL forms project. Save all the files in the same folder. 1. Use the wizard to create the c++ dll project, select c++ & Use VCL checkboxes. Make sure Project Options->C++ Linker->Dynamic RTL is set to true. I also added memmgr.lib and sharemem.obj to the project but I bel...

Calling Java 8 app from Delphi
Hi All: I have been using the procedure below to call a Java program for years. For some reason it no longer works after the machine is upgraded Java 8u25. If fails when it tries to create the process. Any idea of why it would not work with Java 8? Note if I paste the same command line I use in the Delapi XE6 application into a CMD prompt or downgrade to Java 7 it works just fine. Is there a modification to the WinExecAndWait procedure I need to make? Thanks Bob function WinExecAndWait32(CommandLine: string; ShowWindow: Word): DWORD; procedure WaitFor(Pr...

Java Application calling Delphi DLL
Hi All, I have a DLL that doing some staff with a Form written in delphi 2006. This form have some events also. I prepared .NET application. While calling Delphi DLL, Im sending events also from .NET to Delphi DLL. When event occures in Delphi DLL, I can trigger same event from .NET application(written in VS) I think this is called callback functions. Now I have to do same thing in Java Application. Is there anybody know how can I do that? Is there any source to read? Regards. Gurcan YUCEL wrote: > I have a DLL that doing some staff with a Form written in delphi 2006. Th...

Trying to call a .DLL from Delphi XE (used to work with Delphi 6 :-) )
Hi everyone, I have a problem where perhaps some one could help point me in the right direction. In Delphi 6 I used a stand alone package to train a neural netowrk,. The trained neural network was stored as a .DEF file. The standalone software provided a .DLL and Delphi code to call the network and get the prediced values from your sw. (The .DLL was created in 2002 and apparently is 32 bit.) I have'nt used it for years but am now coming back to it.... I now use Delphi XE on Windows 7 (32 bit) The old .exe's I had compiled from that time work fine. However in Delphi XE ...

jni delphi dll vs java app
hi guys! i have wierd problem , i have dll writen in delphi with jni and console java app . All comunication looks like work but dll can't crate form. But if i put showmessage in some export functions form go one . The structure : function start - create hiden form body of start function in dll with jni { Application.Initialize; ExtendedStyle:=GetWindowLong(Application.Handle, GWL_EXSTYLE); SetWindowLong(Application.Handle,GWL_EXSTYLE,ExtendedStyle or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW); Application.MainFormOnTaskbar := false; Application.CreateForm(TForm1, ...

Calling C++ DLL call from Delphi
Hi All I have C++ DLL setup that exports the following function: bool ApplyRule(HANDLE DriverDevice, std::string *Path, PROTECTION_TYPE Type, PROTECTION_ACTION Action, bool Architecture64, bool AddRule) I am not sure how to convert it properly to delphi, inparticular the std::string parameter. ApplyRule : function (DriverDevice : THandle; Path : ????; Kind : PROTECTION_TYPE; Action : PROTECTION_ACTION; Architecture64 : Boolean; AddRule : Boolean) : boolean; stdcall; Thanks for the help. Chris Nillissen wrote: > I am not sure how to convert it properly to delphi,...

Delphi dll
I'm developing a dll file in Delphi 7 in order to use it in a Powerbuilder 10.5 application. I get strange results in PB when i try to pass a string through a function or procedure. I've tried pchar, pwidechar, lpstr, lpctstr in D7 and string or REF string in PB, but nothing seems to be working properly. The function in D7 is quite simple, i just take a string for input, encode it and return an encoded string for output. In PB i get a lot of "squares" in my output string. There seems to be a problem reading (from PB) the memory address that is pointed out from D...

call Delphi-DLL
Hey all, I wanted to call a DLL functions written in Delphi (Pascal). To call the DLL functions I built a Nonvisual-Userobject nvu_call_delphidll in PB6.5 . The PB external function declaration is: FUNCTION long pas_getMin (long x, long y) LIBRARY "MyLib.dll" In the Userobject the code looks like: public function long uf_getmin (long al_x, long al_y); long returnval=0 returnval = pas_getmin(al_x, al_y) return returnval The Delphi 3.0 code for my test DLL is: .... function pas_getMin(x,y: integer): integer; begin if x < y then pas_getMin := x else p...

delphi Win32 using delphi .NET dll
Hi, I'm trying to use a delphi.NET dll in delphi.WIN32. I am currently using CodeGear Delphi 2007 with version2(base version) of .NET I can get the dll to import into the WIN32 application the only problem is when i include things such as: "using Classes,DateUtils, SysUtils" in the .NET dll the win32 application will instantly hang when any of the dll functions are called. Any help would be great thanks. Also I have tried this example and it also crashes for me? http://cc.embarcadero.com/Item/22688 -Braden I also found this.. "The problem is that, wehn you instal...

Delphi XE7 call Java Class, JAR, such as the example of Zxing call
Delphi XE7 call Java Class, JAR, such as the example of Zxing call http://zarko-gajic.iz.hr/firemonkey-mobile-android-ios-qr-code-generation-using-delphi-xe-5-delphizxingqrcode/ Generate interface files with Java2pas: http://www.fmxexpress.com/utility-to-generate-java-android-class-and-jar-file-interfaces-for-delphi-xe5-firemonkey/ Am 14.09.2014 10:08, schrieb ww6 wuxu: > Delphi XE7 call Java Class, JAR, such as the example of Zxing call > Hello, I assume this is some Android related question? If that's the case and the other posted reply isn't yet what you want...

Calling a C++ DLL from Delphi
I use C++ as my main language and nedd to test some stuff with delphi. I have to call a C++ DLL from Delphi. The C++ header is this. class _declspec(novtable) OwnerOfMain { public: virtual void __stdcall DoStatus(long type, long value)=0; }; class _declspec(novtable) Main { public: virtual void __stdcall Delete() = 0; virtual const wchar_t * __stdcall GetTitle() = 0; virtual void __stdcall SetTitle(const wchar_t *) = 0; virtual bool __stdcall Startup(OwnerOfMain *mainOwner)=0; void operator delete(void* p) { if (p) { Main* w = static_cast<Main*>(p)...

Delphi and Delphi for .Net
It seems that Delphi for .Net is slower than Delphi Win32 native applicaiton. I would like to know is it true all .Net application is slower than Win32 native applicaiton or it is Delphi for .Net only. Your information is great appreciated, Inung On 2011-06-21 18:20:17 +0100, Inung Huang said: > It seems that Delphi for .Net is slower than Delphi Win32 native applicaiton. > I would like to know is it true all .Net application is slower than > Win32 native applicaiton or it is Delphi for .Net only. If you are only running the code in the application once then, yes, yo...

Calling Delphi DLL from C#
We have a delphi application that loads the dll dynamically and calls a couple of functions in a Delphi DLL using Load Library, GetProcAddress, and FreeLibrary and all works fine. The DLL is going to be called by a C# application developed in VS 2010. I have the C #code below to test sending and receiving data from the dll and it works ok, but when I close the application or try to resend data, I get an access violation. Do I need to make the calls to the dll using the Load Library, GetProcAddress, and FreeLibrary as well. If so how would I code this in C#? Also I am wondering if I n...

Web resources about - Java app calling a Delphi DLL - embarcadero.delphi.nativeapi

London Calling - Wikipedia, the free encyclopedia
London Calling is the third studio album by the English punk rock band The Clash . It was released in the United Kingdom on 14 December 1979 ...

List of country calling codes - Wikipedia, the free encyclopedia
This is a list of country calling codes defined by ITU-T recommendations E.123 and E.164 , also called IDD ( International Direct Dialling ) ...

Free VoIP Calling Added To Facebook Messenger For IOS In The U.K.
Voice-over-Internet-protocol calling has made its way across the pond for Facebook Messenger users, as the social network updated its iOS version ...

Facebook Video Calling - Facebook
Bring your conversations to life on Facebook. With face-to-face video calling, now you can watch your friends smile, wink and LOL. To get started, ...

Facebook roundup: video ads, voice calling, logos and more
... than three per day at launch. It is unclear whether the ads will autoplay in the feed or not. More Messenger for Android users get free calling ...

Berlin Calling (@neuraum) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Calling all foodies: Here comes @TwitterFood
There are many thousands of food-related Tweets people send on Twitter each day – Tweets about meals, ingredients, favorites, recipes and dining ...

YUBISASHI NIPPON CALLING ENGLISH for iPhone, iPod touch, and iPad on the iTunes App Store
Get YUBISASHI NIPPON CALLING ENGLISH on the App Store. See screenshots and ratings, and read customer reviews.

Calling woman II - Flickr - Photo Sharing!
Explore Marcel Oosterwijk's photos on Flickr. Marcel Oosterwijk has uploaded 2195 photos to Flickr.

Video Calling Coming to WhatsApp Soon: Report
... images show WhatsApp working on a prototype video call feature. Facebook Inc. ( NASDAQ:FB )-owned WhatsApp could soon introduce video calling ...

Resources last updated: 12/28/2015 5:07:55 AM