VC MFC DLL中定义:
struct FieldElement
{
BSTR Name;
BSTR Value;
bool    Sequence;
bool Mandatory;
};long WINAPI ArrayTest(FieldElement *pMySet,long ElementCount)
{
CString _Name;
for (long i=0;i<ElementCount;i++)
{
_Name = (LPCWSTR)(pMySet+i)->Name;
//_Name.Format("%s",(pMySet+i)->Name);
AfxMessageBox(_Name,MB_OK | MB_ICONINFORMATION);
}
return 0;
}
C#调用:
public struct DLLType
{
    public string Name;
    public string Value;
    public bool Sequence;
    public bool Mandatory;
}[DllImport("BSTR.dll", EntryPoint = "ArrayTest",CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int ArrayTest(ref DLLType Key,int Count);private void button1_Click(object sender, EventArgs e)
{
    DLLType []x= new DLLType[6];    x[0] = new DLLType();
    x[0].Name = "sdfasdfa";
    x[1] = new DLLType();
    x[1].Name = "阿斯顿发送的";
    x[2] = new DLLType();
    x[2].Name = "萨法四大阿斯顿发送大苏打";    ArrayTest(ref x[0],3);
}显示的都是乱码,但是在VB中调用显示正常。CharSet 属性更改为 CharSet.Ansi 或 CharSet.Unicode都不能正常显示。请问各位高手该怎么解决?

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        public struct DLLType
            {
                public IntPtr Name;
                public IntPtr Value;
                public bool Sequence;
                public bool Mandatory;
            }        [DllImport("BSTR.dll", EntryPoint = "ArrayTest", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern int ArrayTest(ref DLLType Key, int Count);        DLLType[] x = new DLLType[3]; 
            private void Form1_Load(object sender, EventArgs e)
            {
                x[0] = new DLLType();
                x[0].Name =  Marshal.StringToBSTR("sdfasdfa");
                x[1] = new DLLType();
                x[1].Name =  Marshal.StringToBSTR("阿斯顿发送的");
                x[2] = new DLLType();
                x[2].Name =  Marshal.StringToBSTR("萨法四大阿斯顿发送大苏打");
               
                ArrayTest(ref x[0], 3);
                string s1 = Marshal.PtrToStringBSTR(x[0].Value);
                string s2 = Marshal.PtrToStringBSTR(x[1].Value);
                string s3 = Marshal.PtrToStringBSTR(x[2].Value);
                
            }
        }
    }
      

  2.   

    TO: xingyuebuyu谢谢你的回答,我试了一下,第一个元素的字符串能正确处理,但是第二个显示的和第一个一样,第三个就成了乱码。我想,是不是因为IntPtr数据类型的字节长度和BSTR类型的长度不一样?麻烦再帮忙看一下。
      

  3.   

    已经搞定,是因为C#中bool类型的长度和VC中bool类型长度不一致。感谢各位!