We help IT Professionals succeed at work.

Create C-style string from C# string

adg
adg asked
on
1,559 Views
Last Modified: 2012-05-05
private static void AssignSbyteArray(sbyte* array, string value)
{
      System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
      byte[] ba = encoding.GetBytes(value); // Line A
      int slen = value.Length;
      for (int i = 0; i < slen; i++)
      {
      array[i] = (sbyte)ba[i]; // Line B
      }
      array[slen] = 0;
}

I wrote this snippet to create a c-style string from a c# string. It works ok but there are several things about it that I don't like. The first one is that I'm creating an array in Line A and then copying it in Line B. Is there a way to convert directly into the memory identified by the passed sbyte pointer parameter rather than doing a copy?

Also, I would be happy to take a completely different approach. Please let me know if you have a better way to create a C-style string from a C# string.

Thanks!
Comment
Watch Question

Commented:
What is the purpose of this code? If you want to pass string to unmanaged function, use Marshal.StringToHGlobalAnsi.
adg

Author

Commented:
Hi AlexFM, thanks for your response. I've heard I should be using Marshal but the code I inherited was written in this style where the structs are being passed directly using pointers so that's they way I've been doing it too. It work but I understand that is not the preferred way. The above method is supposed to create a zero-terminated string of 8 bit characters from a c# string and I think it is working OK in the sense that the output is correct.

I'm new at this unmanaged stuff - would I be able to use Marshal in my little method without having to reorganize the entire class? Can you give me an example?  If you have any advice on that I'd appreciate it.  But if I can't do that maybe you can help me to understand if there is a better way to populate the sbyte array.

Thanks!

Commented:
I don't see any problem in AssignSbyteArray function ifself.
My question was - what is the code which calls this function. If the purpose of this code is to call unmamaged function passing sbyte* array - it can be replaced with Marshal.StringToHGlobalAnsi. But I don't see this code so I need to guess.
adg

Author

Commented:
OK, I see. I'll post the calling code in about 12 hours - thanks!
adg

Author

Commented:
I consolidated and simplified this code from several different classes to try to make it clear what is happening.

If this doesn't clarify it, I can work up a test program to illustrate.  

public unsafe struct ControlStruct
{
   public long cacheId;
   public long operationTime;
   public fixed sbyte card[80];
}
 
[DllImport("veryold.dll")]
static extern int Initialization(ref ControlStruct control);

ControlStruct control = new ControlStruct();

control.cacheId = 0;
control.operationTime.timeStamp=0;
AssignSbyteArray(control.card,"Hello");

int rc = Initialization(ref control); // call to DLL
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
adg

Author

Commented:
OK, I'm game - I'll give it a try.  But do you understand that the structure (which is much more complicated than the modified one I showed you) is being used in a bunch of places? Doesn't that mean I'm going to have to change the entire application around instead of just making the small change I had planned? Or am I misunderstanding?

BTW, thanks for your assistance - I appreciate it.
adg

Author

Commented:
>> BTW, .NET long type is 64 bits value, not like in C++ where both long and int are 32 bit.

This comment solved another bug that I caused. I had changed uint to long without realizing it (old habits die hard). That was actually more help than answering my original question.

Commented:
You can decide whether to change sbyte array to string or not - this is your choice. Basically your existing solution works.
adg

Author

Commented:
Yes, it's hard to fix something that isn't actually broken. 8*)  I know the method you showed me is much better than one I'm currently using.  Thanks for your patience and your help.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.