By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,433 Members | 776 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,433 IT Pros & Developers. It's quick & easy.

Marshal::StringToHGlobalAnsi and System.AccessViolationException

P: n/a

I have cross-posted this question to 3 newsgroups since I am not sure
exactly where it belongs (and some NG's have very less activity).
Apologies in advance for this. I have set the followup to the
dotnet.framework.interop NG but feel free to chage it as appopriate.

I have a question regarding converting a Managed System.String^ to
unmanaged const char*.
I inherited a code that does it like this:

String^ s = "00000";
LPCSTR str = static_cast<LPCTSTR>(const_cast<void*>(static_cast <const
void*>(Marshal::StringToHGlobalAnsi(s))));
char someStr[20];
strncpy_s(someStr, 19, str, 19);
someStr[19] = 0;
Marshal::FreeHGlobal(static_cast<IntPtr>(const_cas t<void*>(static_cast<const
void*>(str))));

Leaving aside the fact that there are better ways to accomplish what I
want (like calling .ToPointer() for example) can someone tell me if
that piece of code as it stands has a potential to create problems? I
am getting some System.AccessViolationException around these parts --
although I can't be sure this is what is causing the problem I want to
eliminate it as a potential issue. Here are my issues with that block
of code:

1) It seems to do an unnecessary amount of back-and-forth castings for
what should essentially be cast to a void* and then to a const char*.
First it casts the code to a const void*, then it casts away the const
and then does a cast of const char*. I feel uneasy with so many casts
around.
2) Same with the FreeHGlobal -- too many casts
3) the code that does strncpy seems to be copying more than it
should. I think Marshal::StringTOHGlobalAnsi returns a null-
terminated string. Copying 19 bytes further than seems to be
trampling on memory that doesn't belong to the code.

Any insights?
Feb 27 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.