467,910 Members | 1,676 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,910 developers. It's quick & easy.

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

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
  • viewed: 1651
Share:

Post your reply

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

Similar topics

3 posts views Thread by Salvador | last post: by
3 posts views Thread by Morgan Cheng | last post: by
8 posts views Thread by Notre Poubelle | last post: by
8 posts views Thread by Arjan | last post: by
9 posts views Thread by =?Utf-8?B?RWR3YXJkUw==?= | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.