我正在尝试使用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;
}
测试Cpp.h
#ifndef HEADER_FILE
#define HEADER_FILE
#ifdef __cplusplus
extern "C" {
#endif
void helloWorld();
#ifdef __cplusplus
}
#endif
#endif
测试Cpp.cpp
使用 REST API SDK 从C++调用 REST API C++
#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();
}
}
来自 MyTestCLib.c 你调用 helloWorld 声明为 C,但编译者只创建C++函数版本。此调用失败C++因为函数使用 CPU 注册表和堆栈的方式不同。有一个简单的解决方案。创建具有不同名称的函数的 C 版本。
测试Cpp.h
#ifdef __cplusplus
void helloWorld();
#else
void c_helloWorld();
#endif
测试Cpp.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++函数。