Interacting with a C++ DLL - (new attempt)

G

Guest

Hi, I posted this twice but didn't get any response
Can somebody please help me out of this situation

Unsolved problem ...

I'm new to C# and having a problem with interaction between a (legacy) C++ dll and functions in my C# module. I'm using a third party C++ DLL, no source available (so, not possible to rebuilt it with Managed extensions)
At a certain point in my C#-app I have to return the address of a (managed-) read-buffer into one of the arguments of a callback function, needed by that DLL

The legacy C++ DLL callback interface looks like this
static MC_STATUS MediaToFile( char* Afilename
void* AuserInfo
int* AdataSize
void** AdataBuffer,
int AisFirst
int* AisLast

The fourth callback argument: <void** AdataBuffer> needs to be returned with the address of the managed buffer used in my C# function
I've implemented the above in C# as follows

public delegate int MediaToFile
[MarshalAs(UnmanagedType.LPStr)
string filename
IntPtr info
ref int size
ref IntPtr bufferPtr
int first
ref int last)

..

//Data read in my C#-app are put into CBinfo.buffer
[StructLayout(LayoutKind.Sequential)
public class CBinf

public IntPtr stream
public int messageID
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8192)
public byte[] buffer

..
// Instantiating it
public CBinfo cbi
..

//In the MediaToFile implementation I wrote the following
..
FileStream fs=fi.OpenRead()
nBytesRead=fs.Read(cbi.buffer, 0, nBytes)
..

Next step, the problem: I have to deliver the "cbi.buffer" location (its
address) to the callback argument: "ref IntPtr bufferPtr"
The DLL apparently needs to 'look back' into the buffer data
How to do this
(In C++ I used to write it like this: *AdataBuffer = CBInfo->buffer;

Doing Marshal.nnn / Unsafe / danger of GarbColl moving the buffer....? Please advise - Thank you for your time
 
M

Michael Kelly

Doing Marshal.nnn / Unsafe / danger of GarbColl moving the buffer....? Please advise - Thank you for your time!

You can lock memory against GC relocations with the "fixed" keyword.
Searching the MSDN docs on that will pull up some example code.
As long as you're doing that you may as well mark your function
as "unsafe" and just use the raw pointer declarations instead of
the C#-ified ones. That way you can just duplicate the parameter
definitions and whatnot. That should reduce your worries to
calling conventions and name mangling. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top