C++/CLI error: 'a value type of "int" cannot be used to initialize an entity of type "Department ^"' - c++-cli

My problem is that on the line just above "return temp;" in my CreateNewDepartment function I get a weird compile error (red underline in Visual Studio). When I mouse over the compile error text ("deptId,") in "Department^ temp(deptId, var[0], var[1]);" the pop-up tip says:
a value type of "int" cannot be used to initialize an entity of type "Department ^"
Here is my code to create a new object:
Department^ CreateNewDepartment(SQLRETURN retCode, SQLHANDLE hStmt)
{
int deptId;
String^ Name;
String^ Location;
System::String^ bufN;
char buf[256];
SQLINTEGER numBytes;
for (int i = 1; i <= 3; i++)
{
retCode = SQLGetData(
hStmt,
i, // COLUMN NUMBER of the data to get
SQL_C_CHAR, // DATA TYPE that you expect to receive
buf, // BUFFER to put the data that you expect to receive
255, // BUFFER size in bytes (-1 for null terminator)
&numBytes // SIZE in bytes of data returned
);
if (CHECK(retCode, "SqlGetData", false))
{
bufN = gcnew String((char *)buf);
if (i == 1)
{
std::string s = msclr::interop::marshal_as<std::string>(bufN);
deptId = std::stoi(s, nullptr, 0);
}
else if (i == 2)
{
Name = bufN;
}
else if (i == 3)
{
Location = bufN;
}
}
}
Department^ temp(deptId, Name, Location);
return temp;
}
Department is defined thus:
ref class Department
{
private:
int _deptId;
String^ _deptName;
String^ _deptLocation;
public:
Department(int id, String^ deptName, String^ deptLocation);
<...snip...>
}
And the cstr and set functions:
Department::Department(int id, String^ deptName, String^ deptLocation)
{
setDeptId(id);
setDeptName(deptName);
setDeptLocation(deptLocation);
}
void Department::setDeptId(int id)
{
_deptId = id;
}
void Department::setDeptName(String^ name)
{
_deptName = name;
}
void Department::setDeptLocation(String^ location)
{
_deptLocation = location;
}
Sorry if this is a simple error or dumb question, but I'm new to CLI.

Department^ temp(deptId, Name, Location);
Apparently should have been:
Department^ temp(gcnew Department(deptId, Name, Location));
Although I have no idea why. lol

Related

How to pass custom buffer to windows runtime methods

I am trying to pass my custom buffer to WinRT objects that take IBuffer as argument. Here is what I have so far;
static const uint32_t ARRAY_SIZE = 4096;
struct ArrayBuffer : implements<ArrayBuffer, IBuffer, winrt::impl::IBufferByteAccess>
{
uint32_t Capacity() const { return ARRAY_SIZE; }
uint32_t Length() const { return length; }
void Length(uint32_t value)
{
if (value > ARRAY_SIZE)
throw hresult_invalid_argument();
length = value;
}
int32_t __stdcall Buffer(uint8_t** value)
{
*value = &data[0];
return 0;
}
private:
uint32_t length = 0;
uint8_t data[ARRAY_SIZE];
};
I am trying to use it like this;
fire_and_forget WebSocketServer::readLoop(StreamSocket socket)
{
IBuffer buffer = make<ArrayBuffer>();
auto istream = socket.InputStream();
while (true)
{
try
{
co_await istream.ReadAsync(buffer, ARRAY_SIZE, InputStreamOptions::None);
}
catch (hresult_error const& ex)
{
hresult hr = ex.code();
hstring message = ex.message();
}
if (buffer.Length() == 0)
break;
buffer.Length(0);
}
}
However, I am getting hresult_no_interface exception when I call ReadAsync method.

Arduino - passing values by reference from lamda to singleton

Hello i am bigginer in programing and i have specific problem.
I have been learning a new ways to write a code in small Arduino project.
that project have multiple objects like distance measuring Senzor, led diods , temperature senzor, etc. And all this objects have its own menu where you can, for example, start a calibration or just get values.
What i need is singleton class that has a function enter_esc() that need a int (*funct)() parameter basically function pointer.
That enter_esc(int (*funct)()) function just looping function until you press escape pin which is defined.
function Calibration() have inside some private: object data types like value or cali_value.
so i tried to insert function Calibration() right into enter_esc(Calibration) but it won't compile becouse i didnt pass that vlaues by reference or copy.
but what i found is lambda.
i made a lamda similar to a Calibration() function and i passed values by reference &{//domething;}
but i had to use enter_esc(std::function<int()>& funct) whitch is only int C++ standard library and not in Arduino C/C++ so my qestion is:
[is there some way how to pass values by reference by using lambda to a singleton class in Arduino ?]
(i konw it can be done differently but like i said i want to learn some new ways to program, also if you have some different way to make it i will by very happy to see it)
10Q for your time :)
//Class.h
#pragma once
class events {
private:
static events e_instance;
int p_menu, p_enter, p_esc, p_up, p_down;
int menuValue;
events();
public:
events(const events&) = delete;
static events& Get();
int ArrowUpDown(int maxVal);
int ArrowUpDown(int p_up, int p_down, int maxVal);
int enter_esc(const std::function<int()>& funct);
};
events events::e_instance;
class deviceBase : public Printables
{
public:
const char* a_pin;
int d_pin;
String type;
String deviceName;
bool inUse;
int actualCount;
public:
String getType() override;
int getActualCount() override;
String getName() override;
String getInUse() override;
};
class senzor : public deviceBase
{
private:
int Value;
int triggValue;
public:
int p_triggValue = 10;
static int allSenzors;
friend events;
senzor();
~senzor();
public:
int getValue();
int Calibration();
void changeTriggVal(int x);
void Reset();
void nullCalibration();
void Menu(int x);
void setName(String deviceName);
void setInUse(bool x);
int getPin();
};
int senzor::allSenzors = 0;
if you have some good advice to my code writing i will be also very glad
//Class.cpp
#include <iostream>
#include <string>
#include <functional>
#define LOG(x) std::cout << x << std::endl;
#define PINMENU 12
#define PINENTER 8
#define PINESC 9
#define PINUP 11
#define PINDOWN 13
using String = std::string;
struct Printables
{
virtual String getType() = 0;
virtual int getActualCount() = 0; ;
virtual String getName() = 0;
virtual String getInUse() = 0;
};
#include "Class.h"
events& events::Get() {
return e_instance;
}
int events::ArrowUpDown(int maxVal) {
if (maxVal) {
menuValue = menuValue < maxVal ? menuValue++ : menuValue;
}
if (maxVal) {
menuValue = menuValue > 0 ? menuValue-- : menuValue;
}
return menuValue;
}
int events::enter_esc(const std::function<int()>&funct) {
if (1) {
while (!p_esc) {
auto f = funct;
}
}
return 1;
}
int events::ArrowUpDown(int p_up, int p_down, int maxVal) { return 666; }
events::events() {};
String deviceBase::getType() { return type; }
int deviceBase::getActualCount() { return actualCount; }
String deviceBase::getName() { return deviceName; }
String deviceBase::getInUse() {
String Status;
Status = inUse == 1 ? "Active" : "Deactive";
return Status;
}
senzor::senzor() : Value(0), triggValue(1) {
a_pin = "xx";
type = "[SENZOR]";
deviceName = "[UNKNOWN]";
inUse = 0;
allSenzors++;
actualCount = allSenzors;
a_pin = 0;
}
senzor::~senzor() {
allSenzors = 0;
}
int senzor::getValue() {
Value = 4;
return Value;
}
int senzor::Calibration() {
triggValue = triggValue < getValue() ? getValue() : triggValue;
p_triggValue = triggValue;
return p_triggValue;
}
void senzor::changeTriggVal(int x) {
p_triggValue = x;
}
void senzor::Reset() {
p_triggValue = triggValue;
}
void senzor::nullCalibration() {
triggValue = 1;
}
void senzor::setName(String deviceName) {
this->deviceName = deviceName;
}
void senzor::setInUse(bool x) {
inUse = x;
}
int senzor::getPin() {
return 4;
}
int printsss() {
return 1;
}
////////////////////////////////this what i was writing about//////////////////////////////
void senzor::Menu(int x) {
events::Get().enter_esc([&]() { triggValue = triggValue < getValue() ? getValue() : triggValue;
p_triggValue = triggValue;
return p_triggValue; });
}
but if i use lambda in arduino with enter_esc(int (*funct)()) i get this kind of error
no matching function for call to 'events::enter_esc(senzor::Menu(int)::<lambda()>)'

Inconsistent method declarations in duplicated types

I'm making a class in c++-cli, and I added an extra argument to one of my functions. The name of the extra argument was int row,and when I add that I get this error:
LNK2022 metadata operation failed (80131187) : Inconsistent method declarations in duplicated types (types: query; methods: Read_DB)
When I remove that extra argument I added, the error goes away. If I remove the argument column_index, it also goes away. But if I remove one of the String^ arguments, it still stays. I'm not sure what the error is, here's both my .h and the functions definition in the .cpp file of code:
Header:
#ifndef DATA_BASE
#define DATA_BASE
using namespace System;
using namespace System::Data::SqlClient;
ref class ConnectDB{
protected:
SqlConnection^ cnn;
bool state;
public:
String^ db;
bool ConnectDataBase();
bool DisconnectDataBase(void);
};
ref class Query : public ConnectDB {
private:
~Query(void);
public:
bool Create_Table(String^ name, String^ columns);
String^ Read_DB(String^ column, String^ table, int column_index, int row);
bool Write_DB(String^ path, String^ msg);
};
#endif
cpp file:
String^ Query::Read_DB(String^ column, String^ table, int column_index, int row) {
String^ output;
String^ sql = "SELECT " + column + " FROM " + table;
try {
SqlCommand^ command;
SqlDataReader^ dataReader;
command = gcnew SqlCommand(sql, cnn);
dataReader = command->ExecuteReader();
std::cout << "Reading data from Database...\n";
int counter;
while (dataReader->Read()) {
counter++;
if(counter == row)
output = (String^)dataReader->GetValue(column_index);
}
//command->Dispose();
dataReader->Close();
}
catch (Exception^ e) {
Console::WriteLine(e);
std::cout << "Failed to query database\n";
return "0";
}
return output;
}
to fix the problem I just deleted the debug folder and restarted my application. It had something to do with changing the name of the object.

Passing string array from Borland C++ to C#

I want to pass list of email address strings from Borland C++ to my C# library. Below my C# side code. I could make call to PrintName() method and it works. Now I want to print email addresses, but if I call PrintEmails() function nothing happens. Could you please suggest how I can pass multiple email addresses to C# lib.
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4A686AB1-8425-43D9-BD89-B696BB5F6A18")]
public interface ITestConnector
{
void PrintEmails(string[] emails);
void PrintName(string name);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITestConnector))]
[Guid("7D818287-298A-41BF-A224-5EAC9C581BD0")]
public class TestConnector : ITestConnector
{
public void PrintEmails(string[] emails)
{
System.IO.File.WriteAllLines(#"c:\temp\emails.txt", emails);
}
public void PrintName(string name)
{
System.IO.File.WriteAllText(#"c:\temp\name.txt", name);
}
}
I have imported TLB file of above C# library into RAD Studio and my C++ side code is as below.
interface ITestConnector : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE PrintEmails(LPSAFEARRAY* emails/*[in,out]*/) = 0; // [-1]
virtual HRESULT STDMETHODCALLTYPE PrintName(WideString name/*[in]*/) = 0; // [-1]
};
TTestConnector *connector = new TTestConnector(this);
SAFEARRAYBOUND bounds[] = {{2, 0}}; //Array Contains 2 Elements starting from Index '0'
LPSAFEARRAY pSA = SafeArrayCreate(VT_VARIANT,1,bounds); //Create a one-dimensional SafeArray of variants
long lIndex[1];
VARIANT var;
lIndex[0] = 0; // index of the element being inserted in the array
var.vt = VT_BSTR; // type of the element being inserted
var.bstrVal = ::SysAllocStringLen( L"abc#xyz.com", 11 ); // the value of the element being inserted
HRESULT hr= SafeArrayPutElement(pSA, lIndex, &var); // insert the element
// repeat the insertion for one more element (at index 1)
lIndex[0] = 1;
var.vt = VT_BSTR;
var.bstrVal = ::SysAllocStringLen( L"pqr#xyz.com", 11 );
hr = SafeArrayPutElement(pSA, lIndex, &var);
connector->PrintEmails(pSA);
delete connector;
Below C++ side code worked in my case.
SAFEARRAYBOUND saBound[1];
saBound[0].cElements = nElements;
saBound[0].lLbound = 0;
SAFEARRAY *pSA = SafeArrayCreate(VT_BSTR, 1, saBound);
if (pSA == NULL)
{
return NULL;
}
for (int ix = 0; ix < nElements; ix++)
{
BSTR pData = SysAllocString(elements[ix]);
long rgIndicies[1];
rgIndicies[0] = saBound[0].lLbound + ix;
HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, pData);
_tprintf(TEXT("%d"), hr);
}

Creating a custom CFType

Is it possible to create opaque types not derived from CFTypeRef which can be retained/released with CFRetain/CFRelease? Or how do I derive a new type from a CFType?
I've never done this, but it is possible using private API. In all likelihood it will be dependent on a specific dot release of OS X, since the CF runtime could change from release to release. In any case, CF is open source so I took a look at what CFRuntime does. I was happy to see Apple included an example:
// ========================= EXAMPLE =========================
// Example: EXRange -- a "range" object, which keeps the starting
// location and length of the range. ("EX" as in "EXample").
// ---- API ----
typedef const struct __EXRange * EXRangeRef;
CFTypeID EXRangeGetTypeID(void);
EXRangeRef EXRangeCreate(CFAllocatorRef allocator, uint32_t location, uint32_t length);
uint32_t EXRangeGetLocation(EXRangeRef rangeref);
uint32_t EXRangeGetLength(EXRangeRef rangeref);
// ---- implementation ----
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFString.h>
struct __EXRange {
CFRuntimeBase _base;
uint32_t _location;
uint32_t _length;
};
static Boolean __EXRangeEqual(CFTypeRef cf1, CFTypeRef cf2) {
EXRangeRef rangeref1 = (EXRangeRef)cf1;
EXRangeRef rangeref2 = (EXRangeRef)cf2;
if (rangeref1->_location != rangeref2->_location) return false;
if (rangeref1->_length != rangeref2->_length) return false;
return true;
}
static CFHashCode __EXRangeHash(CFTypeRef cf) {
EXRangeRef rangeref = (EXRangeRef)cf;
return (CFHashCode)(rangeref->_location + rangeref->_length);
}
static CFStringRef __EXRangeCopyFormattingDesc(CFTypeRef cf, CFDictionaryRef formatOpts) {
EXRangeRef rangeref = (EXRangeRef)cf;
return CFStringCreateWithFormat(CFGetAllocator(rangeref), formatOpts,
CFSTR("[%u, %u)"),
rangeref->_location,
rangeref->_location + rangeref->_length);
}
static CFStringRef __EXRangeCopyDebugDesc(CFTypeRef cf) {
EXRangeRef rangeref = (EXRangeRef)cf;
return CFStringCreateWithFormat(CFGetAllocator(rangeref), NULL,
CFSTR("<EXRange %p [%p]>{loc = %u, len = %u}"),
rangeref,
CFGetAllocator(rangeref),
rangeref->_location,
rangeref->_length);
}
static void __EXRangeEXRangeFinalize(CFTypeRef cf) {
EXRangeRef rangeref = (EXRangeRef)cf;
// nothing to finalize
}
static CFTypeID _kEXRangeID = _kCFRuntimeNotATypeID;
static CFRuntimeClass _kEXRangeClass = {0};
/* Something external to this file is assumed to call this
* before the EXRange class is used.
*/
void __EXRangeClassInitialize(void) {
_kEXRangeClass.version = 0;
_kEXRangeClass.className = "EXRange";
_kEXRangeClass.init = NULL;
_kEXRangeClass.copy = NULL;
_kEXRangeClass.finalize = __EXRangeEXRangeFinalize;
_kEXRangeClass.equal = __EXRangeEqual;
_kEXRangeClass.hash = __EXRangeHash;
_kEXRangeClass.copyFormattingDesc = __EXRangeCopyFormattingDesc;
_kEXRangeClass.copyDebugDesc = __EXRangeCopyDebugDesc;
_kEXRangeID = _CFRuntimeRegisterClass((const CFRuntimeClass * const)&_kEXRangeClass);
}
CFTypeID EXRangeGetTypeID(void) {
return _kEXRangeID;
}
EXRangeRef EXRangeCreate(CFAllocatorRef allocator, uint32_t location, uint32_t length) {
struct __EXRange *newrange;
uint32_t extra = sizeof(struct __EXRange) - sizeof(CFRuntimeBase);
newrange = (struct __EXRange *)_CFRuntimeCreateInstance(allocator, _kEXRangeID, extra, NULL);
if (NULL == newrange) {
return NULL;
}
newrange->_location = location;
newrange->_length = length;
return (EXRangeRef)newrange;
}
uint32_t EXRangeGetLocation(EXRangeRef rangeref) {
return rangeref->_location;
}
uint32_t EXRangeGetLength(EXRangeRef rangeref) {
return rangeref->_length;
}
#endif
CoreFoundation itself does not provide any such mechanism, but all Cocoa objects will work with CFRetain and CFRelease. So the only supported answer is: Create a class based on Foundation and CoreFoundation will recognize it as a CFTypeRef.