从C程序访问C ++函数时,收到错误消息“访问冲突读取位置”

时间:2014-12-30 06:50:58

标签: c++ c visual-studio-2010 visual-studio-2012

我正在尝试使用Visual Studio 2012 IDE从 C 程序访问 C ++ 功能。当我调试时,我在TestCpp.cpp中得到以下错误,方法:helloworld(),行:http_client cli( U("http://localhost:55505/api/Notification"));

MyTestCLib.exe中0x0000000076D23290(ntdll.dll)的未处理异常:0xC0000005: 访问冲突读取位置0x00000621BC90B128。

请在下面找到代码段。

MyTestCLib.c

#include <ctype.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <my_global.h>
#include <mysql.h>
#include <m_ctype.h>

#include "TestCpp.h"

int main()
{
    helloWorld();
    return 0;
}

TestCpp.h

#ifndef HEADER_FILE
 #define HEADER_FILE

 #ifdef __cplusplus
     extern "C" {
 #endif
         void helloWorld();
 #ifdef __cplusplus
     }
 #endif

 #endif

TestCpp.cpp

//使用C ++ REST API SDK从C ++调用REST API

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <iostream>
#include "TestCpp.h"

using namespace utility;                    // Common utilities like string conversions
using namespace web;                        // Common features like URIs.
using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features
using namespace concurrency::streams;       // Asynchronous streams
using namespace std;


void helloWorld()
{

        http_client cli( U("http://localhost:55505/api/Notification") );

        ostringstream_t uri;
        uri << U("/PostNotification");

        json::value bodyarray = json::value::array();

        json::value body = json::value::object();
        body[U("TicketNumber")] = json::value::string( U("25868") );
        body[U("NotificationMessage")] = json::value::string( U("Test Notification Message") );

        bodyarray[0] = body;

        http_response response = cli.request( methods::POST, uri.str(), bodyarray.serialize(), U("application/json") ).get();
        if ( response.status_code() == status_codes::OK &&
            response.headers().content_type() == U("application/json") )
        {
            json::value json_response = response.extract_json().get();
            ucout << json_response.serialize() << endl;
        }
        else
        {
            ucout << response.to_string() << endl;
            getchar();
        }
}

1 个答案:

答案 0 :(得分:0)

来自MyTestCLib.c您调用声明为C的helloWorld,但编译器仅创建C ++函数版本。这个调用faill因为C ++函数使用CPU注册表和堆栈不同的方式。有简单的解决方案。创建具有不同名称的C版函数。

TestCpp.h

#ifdef __cplusplus
void helloWorld();
#else
void c_helloWorld();
#endif

TestCpp.cpp

#include "TestCpp.h"

void helloWorld(void) 
{ 
    /* cpp code */ 
}

extern "C" {
    void c_helloWorld(void)   // C version of helloWorld
    { 
        helloWorld();         // call cpp helloWorld
    }
}

扩展名为.c的源文件由C-Compiler编译。它无法调用C ++函数。但是在C ++ Compler编译的.cpp文件中,您可以创建C函数。这个“C”函数(c_helloWorld)由C ++编译器编译而来,可以从C-Complier中调用。它也可以调用C ++函数。