Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

c# - marshalling a struct containing string

i basically want to take int name and string age from user in c# and send it to dll method written in c which take int and char[50] arguments in it and return string .i created following scenario but i am failed ,any body has the code

i have a dll developed in c which ahas a structure

struct Argument 
{
int age;
char name[50];
} ;

and a method

extern "C"
{
    __declspec(dllexport) Argument FillData(Argument data)
 {
        Argument mydata;

        mydata.age=data.age;
        for(int i=0;i<=sizeof(data);i++)
        {
            mydata.name[i]=data.name[i];

        }
        return mydata;

 }

i declare it in c# in Cs_dll.cs

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
    public struct Argument
    {
        public int age;
        [MarshalAs(UnmanagedType.TBStr)]
        //public char name;
       public char[] name;

    };
  public  class Cs_Dll
    {
      [DllImport("TestLib.dll")]
            public static extern Argument FillData (Argument data);


    }

now againts a button iwant to do

 private void button1_Click(object sender, EventArgs e)
        {
            Argument data=new Argument();
            data.age=Convert.ToInt32(textBox_age.Text);
            char[] name={'a','b','r','a','r', ' ', 'a', 'h', 'm', 'e', 'd', '' };
            for (int i = 0; i <= name.Length; i++)
            {
                data.name[i] = name[i];
            }

               // Array.Copy(name, data.name, name.Length);


            Argument result = Cs_Dll.FillData(data);
            textBox_get.Text = result.age.ToString();
            textBox_age.Text = result.name.ToString();

        }

but i am stuck with error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to change your struct definition of Argument to either


[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Argument
{
    public int age;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
    public string name;
}

- or -


[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
unsafe public struct Argument
{
    public int age;
    fixed char name[50];
}

You might also find the article Default Marshaling for Strings helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...