从C#调用C ++ DLL - System.AccessViolationException

时间:2015-08-06 13:43:02

标签: c# c++ pinvoke dllimport

当试图在C#中调用C ++ DLL时,遇到异常(System.AccessViolationException),我不明白为什么。 C#和C ++项目都是用x64编译的。在Dll.cpp中导出dll方法。在此方法中,使用名为OpcClient的类,该类位于同一项目中。我的IDE是Visual Studio Express 2012。 有人可以帮忙吗?

C#代码:

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

namespace OCTTester
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] array = new string[2];
      array[0] = "Tag1";
      array[1] = "Tag2";
      Connect("IBHSoftec.IBHOPC.DA", array, 2, 0, 100);
      Add("Tag1", 10);
      Stop();
    }

    [DllImport(@"OPCClient.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern void Connect(string hostname, string[] tagnames, int amount_tags, int buffertype, int refreshrate);

    [DllImport(@"OPCClient.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern void Add(string tagname, double value);

    [DllImport(@"OPCClient.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern void Stop();
  }
}

C ++代码(Dll.cpp):

#include "stdafx.h"
#include <exception>
#include "OpcClient.h"

using namespace std;
extern "C" {          // we need to export the C interface
  std::thread *output_thread = NULL;

  _declspec(dllexport) int __cdecl Connect(const char *hostname, const char **tagnames, int amount_tags, int buffertype, int refreshrate)
  {
    OpcClient* opc_client = OpcClient::getInstance();

    vector<string> vec_tagnames;
    for (int i = 0; i < amount_tags; i++)
    {
      vec_tagnames.push_back(tagnames[i]);
    }

    try
    {
      opc_client->Connect(hostname, vec_tagnames, refreshrate, buffertype);
    }
    catch(exception &e)
    {
      std::cout << e.what() << "\n";
      return -1;
    }

    output_thread = new thread(&OpcClient::Start, opc_client);

    return 0;
  }

  _declspec(dllexport) int __cdecl Add(const char *tagname, double value)
  {
    OpcClient* opc_client = OpcClient::getInstance();
    opc_client->AddValueToBuffer(tagname, value);

    return 1;
  }

    _declspec(dllexport) int __cdecl Stop(void)
    {
        OpcClient* opc_client = OpcClient::getInstance();
    opc_client->stop_ = true;
    output_thread->join();

    return 1;
    }

}

0 个答案:

没有答案