[英]While accessing C++ function from C program, getting error message “Access violation reading location”
我正在嘗試使用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。
請在下面找到代碼段。
#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;
}
#ifndef HEADER_FILE
#define HEADER_FILE
#ifdef __cplusplus
extern "C" {
#endif
void helloWorld();
#ifdef __cplusplus
}
#endif
#endif
//使用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();
}
}
從MyTestCLib.c中,您可以將helloWorld聲明為C,但complier僅創建C ++函數版本。 此調用失敗,因為C ++函數使用CPU注冊表並以不同的方式進行堆棧。 有一個簡單的解決方案。 用不同的名稱創建C版本的函數。
#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 ++函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.