Passing a structure from c++ into a LIB written in c# using Framework 4.0 RRS feed

  • Question

  • I don't know much about c#, but I need to create a c# lib that can be called from c++.  The functions in c# need to receive a structure of data.  My code is listed below:

    c++  (LIB is included in project)

        struct Name
            char FileName[100];
            char FileVersion[100];

        Name  szFile;

        VisionScape Vs;
        Vs.LoadCameraWithConfigFile( szFile);

    c# LIB

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;

    namespace MicroScanFrontRunner
        public class VisionScape
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            public struct Name
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
                public string FileName;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
                public string FileVersion;

            public int LoadCameraWithConfigFile( Name sName )
                int value;
                value = 2;
                return value;

    I am getting the following compiler error:

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    C2664    'int MicroScanFrontRunner::VisionScape::LoadCameraWithConfigFile(MicroScanFrontRunner::VisionScape::Name)': cannot convert argument 1 from 'InitializeScanner::Name' to 'MicroScanFrontRunner::VisionScape::Name'    MicroScan    C:\Users\efthss\Desktop\Plant Moves\MicroScan Vision\C dll\MicroScanCamreaGige\MicroScan.cpp    100    

    Wednesday, February 6, 2019 9:05 PM

All replies

  • You cannot create C# classes from C++ code. This is not a supported situation. Nor can you go the other way unless you're using C++/CLI. You have limited options. The first option is to implement a COM interface in your C# code and then load the code in your C++ app as COM. This is as close to using a C# class as you can get. The alternative approach is to define callbacks that your native code calls that can point to a managed function.

    Also note that you cannot simply load a C# assembly in C++ code. The CLR has to be running to support managed code. It really sounds like you need to be using COM here. Note that you can load native DLLs inside a managed process and this is supported but you're going the other way here.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, February 7, 2019 2:59 PM
  • Have you tried ‘MicroScanFrontRunner::VisionScape::Name szFile’ instead of ‘Name szFile’?

    Thursday, February 7, 2019 5:00 PM