How to pass Delphi stream to c / C ++ library

Is it possible to pass a Delphi stream (stream descendant) to a DLL written in c / C ++? The DLL will be written in Microsoft c / C ++. If this is not possible, what about using C ++ Builder to create a DLL? Also, are there Stream (FIFO) classes that can be used in conjunction with Microsoft C / C ++ and Delphi?

Thanks!

+4
source share
2 answers

You can do this using IStream and TStreamAdapter . Here is a brief example (tested in D2007 and XE2):

uses ActiveX; procedure TForm1.DoSomething; var MemStream: TMemoryStream; ExchangeStream: IStream; begin MemStream := TMemoryFile.Create; try MemStream.LoadFromFile('C:\Test\SomeFile.txt'); MemStream.Position := 0; ExchangeStream := TStreamAdapter.Create(MemStream) as IStream; // Pass ExchangeStream to C++ DLL here, and do whatever else finally MemStream.Free; end; end; 

Just in case, if you need to go the other way (getting IStream from C / C ++), you can use TOleStream to switch from this IStream to Delphi TStream .

+12
source
  • Code compiled by Microsoft C / C ++ cannot call methods directly on a Delphi object. You would have to wrap the methods up and present, for example, C ++ code, interface .
  • Code compiled by C ++ Builder can call methods directly on a Delphi object.

In general, terminating the Delphi class and representing it as an interface not completely trivial. One reason you can't just expose raw methods through an interface is because Delphi methods use a register calling convention, which is owned by Embarcadero compilers. You will need to use a calling convention that is understood by the Microsoft compiler, for example. stdcall .

Another complication is related to exceptions. You will need to make sure that your interface methods do not throw exceptions, since your C ++ code cannot catch them. One option is to use the Delphi safecall calling safecall . The convention of calling safecall stdcall , but with an added twist that converts exceptions to HRESULT values.

Everything is pretty straightforward in concept, but probably requires a certain amount of tedious template.

Fortunately, in the case of TStream you can use the TStreamAdapter to display a Delphi stream as a COM IStream . In fact, the source code for this small class shows how to handle the problems described above.

+4
source

All Articles