Click here to Skip to main content
15,895,423 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I see a problem when call function from dll file which compiled in C++, dll file with functions code as follow:

C++
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>

char* str;
int _stdcall inputt(char* str_)
{
	str=str_;
	return 1;
}

int _stdcall Shooow()
{
	MessageBoxA(NULL,str,"Message...",MB_OK);
	return 0;
}


In this, I export two function inputt() and Shooow(). Dll file named "TestCCCC.dll". Then I call them in C# code as follow:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace muWrapper
{
    public partial class WndSample : Form
    {
        [DllImport("TestCCCC.dll")]
        private static extern int inputt(string FuncName);
        [DllImport("TestCCCC.dll")]
        private static extern int Shooow();

      public WndSample()
      {
        InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
          int ret = inputt("aaaaaa");
          ret = Shooow();
      }
    }
}



When I run it, click the button with the first time, it show a message box with strange characters, not "aaaaaa" !!!? Continue to click with the second time, it show truly with "aaaaaa", and continue...and show truly and truly....

Tell me what was happen in this problem? How to code two function inputt() and Shooow() to show truly at the first time? Thanks.

What I have tried:

I try and try to think about this but not success !
Posted
Updated 21-May-16 5:18am

1 solution

You need to marshall the string into a fixed ASCII character array for the C++ code to use. Your dll should also save the entire string rather than just a pointer, as there is no guarantee that the string will still exist at the call to Shooow().
 
Share this answer
 
Comments
Andrewpeter 21-May-16 21:54pm    
Yes Sir, I have solved this. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900