Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written the code both in VC++ and C# but don't know how to get the string returned
from C to C#...

What I have tried:

VC++ Code:-
In Ctest1.h
#include<stdio.h>
#include "pch.h"
#pragma once
class __declspec(dllexport) Ctest1
{
  public:
  Ctest1();
  ~Ctest1();
  char* func();
};

In Ctest1.cpp
#include "pch.h"
#include "Ctest1.h"
char* Ctest1::func()
{
  char sname[] = { "kkk" };
  return sname;
}
Ctest1::Ctest1()
{}
Ctest1::~Ctest1()
{}

In Caller.h
#include "Ctest1.h"
#include "pch.h"
#ifdef __cplusplus
extern "C"
{
#endif
extern __declspec(dllexport) Ctest1* _Create();
extern __declspec(dllexport)void dispose(Ctest1* _pObject);
extern __declspec(dllexport)char* func(Ctest1* _pObject);
#ifdef __cplusplus
}
#endif

In Caller.cpp:-
#include "pch.h"
#include "Caller.h"
Ctest1* _Create()
{
  //Ctest1 c = new Ctest1();
  return new Ctest1();
}
void dispose(Ctest1* _pObject)
{
  if (_pObject != NULL)
  {
    delete _pObject;
    _pObject = NULL;
  }
}
char* func(Ctest1* _pObject)
{
  if (_pObject != NULL)
  {
    char* str = _pObject->func();
    return str;
  }
}

And in C# Code:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
  public partial class Form1 : Form
  {
    [DllImport("First.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr _Create();
    [DllImport("First.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void dispose(IntPtr pCtest1);
    [DllImport("First.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr func(IntPtr pTest);
    
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      IntPtr ptestClass = _Create();
      IntPtr p= func(ptestClass);
      /// Now how to get the string in C-function 
      dispose(ptestClass);
    }
  }
}

So sir how to get the string returned from C++ and store it in C#
Posted
Updated 3-Jul-20 20:05pm
v2

1 solution

 
Share this answer
 

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