lstrcpy not updating passed in string
I'm trying to use kernel32.dll's lstrcpy to get a string from a pointer in C#, but it isn't working. lstrlenA IS working, it gives me the length of the string, so I'm hitting the kernel32.dll at least. lstrcpy is working in the VB6 app I'm converting, so I know it CAN work, but I don't have a clue why it isn't here.
The string s neve开发者_如何学编程r gets filled with the actual string, it just returns the initial padded string.
[DllImport("kernel32.dll", EntryPoint = "lstrlenA", CharSet = CharSet.Ansi)]
private static extern int lstrlen( int StringPointer );
[DllImport( "kernel32.dll",EntryPoint = "lstrcpyA", CharSet = CharSet.Ansi )]
private static extern int lstrcpy(string lpString1, int StringPointer );
private static string StringFromPointer(int pointer)
{
//.....Get the length of the LPSTR
int strLen = lstrlen(pointer);
//.....Allocate the NewString to the right size
string s = "";
for (int i = 0; i < strLen; i++)
s += " ";
//.....Copy the LPSTR to the VB string
lstrcpy(s, pointer);
return s;
}
I suspect that it might be something to do with managed strings being immutable, so that whenever you think you're changing it, you're actually creating a new string and change the reference to look at the new string instead.
I'm not sure how that works when you use windows API functions, but it's possible that during the call to lstrcpy
a new string is created containing the text that the pointer points to, but because lstrcpy
might not be aware of System.String
, it doesn't handle it properly and so it doesn't change s
to reference the new string.
I think that what you want to use is a Text.StringBuilder
since that's not immutable.
精彩评论