Majak
Majak

Reputation: 1633

Win API method call working in app built in MS VS2008, but not in VS2012

I have Win7 64bit. In my project, I'm using Win API functions from user32.dll for DDE communication. In MS VS2008, everything worked without problems, but now I'm trying to upgrade project to MS VS2012 (on the same PC and OS) and API function call leads to program crash.

It is specifically this function:

[DllImport("user32.dll", EntryPoint = "DdeAccessData", CharSet = CharSet.Ansi)]
    internal static extern string DdeAccessDataString(IntPtr p, out int datasize);

And it's call:

string result = Dde.DdeAccessDataString(da, out datasize);

I'm trying to debug it someway, but without success. I'm only able to to get message, that "Windows has triggered a breakpoint" on this line.

Can you suggest any approach how make it working?

Upvotes: 1

Views: 206

Answers (1)

yms
yms

Reputation: 10418

You cannot use the return value of DdeAccessData directly, since the marshaller does not have a way to know the size of the data that is being returned.

I have not tested this, but something you can try instead is to use IntPtr as return value:

[DllImport("user32.dll", EntryPoint = "DdeAccessData")]
    internal static extern IntPtr DdeAccessData(IntPtr p, out int datasize);

Then use Marshal.ReadByte to retrieve the data.

IntPtr ptrByteArray = Dde.DdeAccessDataString(da, out datasize);
byte[] data = new byte[datasize];
for(int i =0; i < datasize; i++)
{
    data[i] = Marshal.ReadByte(ptrByteArray, i);
}
string result = System.Text.Encoding.ASCII.GetString(data);

You need to call DdeUnaccessData once you are done.

Dde.DdeUnaccessData(da);

Upvotes: 1

Related Questions