我用C#注册api函数写内存,用c++去读,结果c#写进去的字符串,在C++读出来的只有字符串的第一位,不知道是什么原因。高人帮忙啊!!!!结果例如:
c#  input : "testforstring"
C++ ooutput:  "t"代码如下:
1)api 注册
[DllImport("Kernel32.dll")]
internal static extern void CopyMemory(int dest, int source, int size);
2)C#调用
private IntPtr nativePointer = IntPtr.Zero;//OpenFileMapping();MapViewOfFile()得到的结果private unsafe void CopyStreamToSharedMemory( string str )
{
char[] schar = new char[256];
 schar = str.ToCharArray(); // Copy the char array to shared memory
fixed( char* source = schar)
{
void* temp = nativePointer.ToPointer(); byte* dest = (byte*)temp;

CopyMemory( (int)dest,  (int)source, (int)str.Length);
}
}3)C++读取
pBuf_forloop = (LPCTSTR)MapViewOfFile(hMapFile,    // handle to mapping object
FILE_MAP_ALL_ACCESS,  // read/write permission
0,                    
0,                    
BUF_SIZE);                    strcpy(buffer, pBuf_forloop);
printf(buffer);
printf("\n");

解决方案 »

  1.   

    strcpy(buffer, pBuf_forloop); //查一下pBuf_forloop的值是多少
      

  2.   

    没有报错!应该是环境问题。是c++(MFC)和C#对内存的操作不同。比如C# char[]如果每一个元素后面都加\0,那在c++的char[]后面没有,就可能出现问题。C++读到\0就结束了。有没有什么好的方法,最好是例子!~
      

  3.   

    这个问题我碰到过,因为api函数内型不匹配造成的。
    api中的long相当于c#中的interger
      

  4.   

    解决!!!char* GetStr(LPCTSTR Arg)
    {
    char temp[BUF_SIZE] ;
    char * buffer;
    int i = 0;
    int j = 0;
    while(true)
    {
    if(Arg[j] == '!')
    break;
    if(Arg[j] == '\0' || Arg[j] == 'Ì')
    {
    j++;
    continue;
    }
    temp[i] = Arg[j];
    i++;
    j++;
    }
    temp[i++] = '\0';
    buffer = new char[i-1];
    strncpy(buffer, temp, i);
    return buffer;
    }
      

  5.   

    就是方法太笨了!!谁有简单的................HOPE