Error when I try to open cdrom programmatically

V

Victor

Hi guys
when i try to open my cdrom with "mciSendString" API Call. i get exception.
but i have no idea how this happen. Can you guys give me some idea? Thanks

My code likes:
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
private static extern long mciSendString(string lpstrCommand, string
lpstrReturnString, long uReturnLength, long hwndCallback);

private long retvalue;
private string returnstring = string.Empty;

private void button1_Click(object sender, EventArgs e)
{
CDControl(true);
}

private void CDControl(bool action)
{
if (action)
{
// open the CDROM
retvalue = mciSendString("set CDAudio door open",
returnstring, 127, 0);
}
else
{
// Close the CDROM
retvalue = mciSendString("set CDAudio door closed",
returnstring, 127, 0);
}
}

The exception is
PInvokeStackImbalance was detected
Message: A call to PInvoke function
'WindowsApplication1!WindowsApplication1.Form1::mciSendString'
has unbalanced the stack. This is likely because the managed PInvoke
signature does not match the unmanaged target signature.
Check that the calling convention and parameters of the PInvoke signature
match the target unmanaged signature.
 
C

Chris Taylor

Hi,

The problem is with your interop signature it should be more like the
following

[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
private static extern long mciSendString(string lpstrCommand,
string lpstrReturnString, int uReturnLength, IntPtr hwndCallback);

long is 64bit, and the function is expecting 32bit arguments, int is fine
here
unless you expect a rediculously long string.

In you calling code you are expecting a 127 characters, you should precreate
the
string buffer to contain space for 127 characters

returnstring = new string(' ', 127);

In fact I would rather use a StringBuilder in the signature.

[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
private static extern long mciSendString(string lpstrCommand,
StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback);

in which case the returnstring is initialized as follows

returnstring = new StringBuilder(127);

Hope this helps
 

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