C# marshal string PTCHAR TCHAR* help needed

M

Mo

Hi, i am trying to call A dll FUNCTION from a C# application.
i am using this function

int hhpGetErrorMessage(PTCHAR ptcErrorMsg,int nMaxChars)
where
ptcErrMsg: TCHAR buffer to hold error message string.
nMaxChars: Maximum number of characters that can fit in ptcErrorMsg
including NULL.

i defined this function in C# as
// Miscellaneous Error Code Message function.
[DllImport("hhpImgrSdk.dll", CharSet=CharSet.Auto)]
public static extern int hhpGetErrorMessage(string ptcErrorMsg,int
nMaxChars );

i call this function as

string s();
hhpGetErrorMessage(s,128);

i get an error message " Use of unassigned local variable 's'"

when i declare s as string s =new string (' ',128);

it seems to pass the error msg, but the result i get from s is junk
a junk value such as "œ—ž¾'Ì•Š"¬⁤ œäûr"

i know ptcErrorMsg will hold the error msg returned by
hhpGetErrorMessage()
when i tried to change my function to accept a ref to a string such as
[DllImport("hhpImgrSdk.dll", CharSet=CharSet.Auto)]
public static extern int hhpGetErrorMessage(ref string ptcErrorMsg,int
nMaxChars );

i got an Exception "An unhandled exception of type
'System.ExecutionEngineException'"

i dont know for sure if its a Marshaling problem?
i know that PTCHAR,TCHAR* can be substituted in C# by string..
i cannot change the DLL !!
how do i declare a string of a certain size without an initial value

any idea?

thanks all
Mo
(e-mail address removed)
 
N

Nicholas Paldino [.NET/C# MVP]

Mo,

You want to make the declaration like this:

[DllImport("hhpImgrSdk.dll", CharSet=CharSet.Auto)]
public static extern int hhpGetErrorMessage(StringBuilder ptcErrorMsg, int
nMaxChars);

And then call it like this:

// Allocate a StringBuilder.
StringBuilder pobjErrorMsg = new StringBuilder(128);

// Now make the call.
hhpGetErrorMessage(pobjErrorMsg, pobjErrorMsg.Capacity);

Hope this helps.
 
M

mo A

Hi Nicholas,,

That worked great,, but i had to change CharSet to CharSet.Ansi, cause
CharSet.Auto

gave me some junk..

i really appreciate it.

take care

Mo



*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 

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