Re: Sending a buffer to C++ DLL

Tech-Archive recommends: Speed Up your PC by fixing your registry



dollardan@xxxxxxxxxxx wrote:
I've read through the forum and I couldn't get my code to run with any
of the solution I found there.

My project has 3 main components:
Legacy.dll - unmanaged C++
DotNet.dll - C# Class Library. Interop for the Legacy DLL
TestApp.exe

My Problem:
I'm trying to send a buffer to the DotNet.dll from the TestApp for it
to forward to the Legacy.dll. I an having trouble writing the DLL and
calling its methods.
The buffer only contains data that I want the Legacy DLL to read.
That's it. It seems simple enough to do, but I keep tripping the
AccessViolationException:
Attempted to read or write protected memory. This is often an
indication that other memory is corrupt.

Legacy DLL:
bool SetData( UCHAR *buffer, int size);

DotNet DLL:
public static class DotNet
{
[DllImport("Legacy.dll")]
public static extern bool SetData(String buffer, int size);
}

Two important things missing here: you must inform the marshaler that the string is not Unicode (as I presume it's not), and that the bool you're returning is a C++ bool rather than a Win32 BOOL.

[DllImport("Legacy.dll", CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool SetData(string buffer, int size);

With these changes, it should just work:

string input = "Hello there!";
SetData(input, input.Length);

Note that it's vitally important that the string you pass to SetData is not modified. Otherwise, you need to use StringBuilder to marshal the data across instead.

--
J.
.



Relevant Pages

  • Re: overloading +=
    ... If you do this initializing of string, you cannot do deletestring in ... don't Operator+ must return a MyString& ??? ... Where are you allocating inString.string buffer? ... > bool operator< ...
    (comp.lang.cpp)
  • Re: a *working* PostThreadMessage() implementation...?
    ... road if you add a secondary message loop for some reason. ... // add a new message to queue ... BOOL PostThreadMessage; ... // deflate queues buffer ...
    (microsoft.public.vc.mfc)
  • Re: a *working* PostThreadMessage() implementation...?
    ... queue is enormous and is not affected by other threads. ... QUAD qCommand; ... bool _MsgBufferStart; ... // free all memory used by message buffer, ...
    (microsoft.public.vc.mfc)
  • Re: a *working* PostThreadMessage() implementation...?
    ... queue is enormous and is not affected by other threads. ... QUAD qCommand; ... bool _MsgBufferStart; ... // free all memory used by message buffer, ...
    (microsoft.public.vc.mfc)
  • Sending a buffer to C++ DLL
    ... The buffer only contains data that I want the Legacy DLL to read. ... static private String myBuffer = new String; ... static private StringBuilder myBuffer = new StringBuilder(new ...
    (microsoft.public.dotnet.languages.csharp)