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

C# - How to pin the StringBuilder Object when passing to Unmanaged Code

P: 1
Hello,

I need to pass a StringBuilder object to a custom unmanaged DLL. The code most of the time works great, however once in a while I get "Object reference not set to an instance of an object" which means the GC moved the address of StringBuilder object while managed code is writing to it.

I have tried GC.keepalive already. GCHandle.allc and Marshal.alloc doesn't seem to be possible with this type of object. I need the equivalent of (__pin *) in managed C++ to pin the object somehow.

Expand|Select|Wrap|Line Numbers
  1. UpdateStatus(DWORD type, DWORD action, LPTSTR buffer, DWORD bufferSize);
  2.  
  3. DLL Declare
  4. private static extern int UpdateStatus(int type, int action, StringBuilder buffer, int bufferSize);
  5.  
Expand|Select|Wrap|Line Numbers
  1. StringBuilder buffer = new StringBuilder(256);
  2. // error happens here.
  3. UpdateStatus(1, 1, buffer, buffer.Capacity); 
  4.  
Note that I am careful inside the DLL not to write passed the end of size passed.

Expand|Select|Wrap|Line Numbers
  1. StringBuilder buffer = new StringBuilder(256);
  2. // this obviously always works 
  3. UpdateStatus(1, 1, null, 0); 
  4.  
Any suggestions is greatly appreciated.
Thanks.
Feb 20 '07 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.