how to pass char pointer to function and return another string in ( C )? - function-pointers

i have a code to find table name in SQL query . i create function to check char pointer and i need return table name string .
my function
char* SQLParser_GetTable(char *query)
{
const char *str = "my string";
return *str;
}
void PrintRows(char *TableName)
{
}
void doSELECT(char *query)
{
printf("do SELECT :");
PrintRows(SQLParser_GetTable(*query));
}

const char* SQLParser_GetTable(char *query)
{
const char *str = "my string";
return str;
}

Related

How to replace n occurrence of a substring in a string in dart?

I want to replace n occurrence of a substring in a string.
myString = "I have a mobile. I have a cat.";
How I can replace the second have of myString
hope this simple function helps. You can also extract the function contents if you don't wish a function. It's just two lines with some
Dart magic
void main() {
String myString = 'I have a mobile. I have a cat.';
String searchFor='have';
int replaceOn = 2;
String replaceText = 'newhave';
String result = customReplace(myString,searchFor,replaceOn,replaceText);
print(result);
}
String customReplace(String text,String searchText, int replaceOn, String replaceText){
Match result = searchText.allMatches(text).elementAt(replaceOn - 1);
return text.replaceRange(result.start,result.end,replaceText);
}
Something like that should work:
String replaceNthOccurrence(String input, int n, String from, String to) {
var index = -1;
while (--n >= 0) {
index = input.indexOf(from, ++index);
if (index == -1) {
break;
}
}
if (index != -1) {
var result = input.replaceFirst(from, to, index);
return result;
}
return input;
}
void main() {
var myString = "I have a mobile. I have a cat.";
var replacedString = replaceNthOccurrence(myString, 2, "have", "had");
print(replacedString); // prints "I have a mobile. I had a cat."
}
This would be a better solution to undertake as it check the fallbacks also. Let me list down all the scenarios:
If position is 0 then it will replace all occurrence.
If position is correct then it will replace at same location.
If position is wrong then it will send back input string.
If substring does not exist in input then it will send back input string.
void main() {
String input = "I have a mobile. I have a cat.";
print(replacenth(input, 'have', 'need', 1));
}
/// Computes the nth string replace.
String replacenth(String input, String substr, String replstr,int position) {
if(input.contains(substr))
{
var splittedStr = input.split(substr);
if(splittedStr.length == 0)
return input;
String finalStr = "";
for(int i = 0; i < splittedStr.length; i++)
{
finalStr += splittedStr[i];
if(i == (position - 1))
finalStr += replstr;
else if(i < (splittedStr.length - 1))
finalStr += substr;
}
return finalStr;
}
return input;
}
let's try with this
void main() {
var myString = "I have a mobile. I have a cat.I have a cat";
print(replaceInNthOccurrence(myString, "have", "test", 1));
}
String replaceInNthOccurrence(
String stringToChange, String searchingWord, String replacingWord, int n) {
if(n==1){
return stringToChange.replaceFirst(searchingWord, replacingWord);
}
final String separator = "#######";
String splittingString =
stringToChange.replaceAll(searchingWord, separator + searchingWord);
var splitArray = splittingString.split(separator);
print(splitArray);
String result = "";
for (int i = 0; i < splitArray.length; i++) {
if (i % n == 0) {
splitArray[i] = splitArray[i].replaceAll(searchingWord, replacingWord);
}
result += splitArray[i];
}
return result;
}
here the regex
void main() {
var myString = "I have a mobile. I have a cat. I have a cat. I have a cat.";
final newString =
myString.replaceAllMapped(new RegExp(r'^(.*?(have.*?){3})have'), (match) {
return '${match.group(1)}';
});
print(newString.replaceAll(" "," had "));
}
Demo link
Here it is one more variant which allows to replace any occurrence in subject string.
void main() {
const subject = 'I have a dog. I have a cat. I have a bird.';
final result = replaceStringByOccurrence(subject, 'have', '*have no*', 0);
print(result);
}
/// Looks for `occurrence` of `search` in `subject` and replace it with `replace`.
///
/// The occurrence index is started from 0.
String replaceStringByOccurrence(
String subject, String search, String replace, int occurence) {
if (occurence.isNegative) {
throw ArgumentError.value(occurence, 'occurrence', 'Cannot be negative');
}
final regex = RegExp(r'have');
final matches = regex.allMatches(subject);
if (occurence >= matches.length) {
throw IndexError(occurence, matches, 'occurrence',
'Cannot be more than count of matches');
}
int index = -1;
return subject.replaceAllMapped(regex, (match) {
index += 1;
return index == occurence ? replace : match.group(0)!;
});
}
Tested on dartpad.

Wrapping libcups C library in Swift

I am trying to wrap the libcups library https://github.com/apple/cups to be used in my Swift project.
I have tried some of the examples in https://www.cups.org/doc/cupspm.html and they are working fine.
However I am struggling when it comes to wrapping the C code to be used in a Swift project.
I have been searching online on how to wrap C libraries in Swift but has not been able to have much progress.
Here is the C code
#include <stdio.h>
#include <cups/cups.h>
typedef struct {
int num_dests;
cups_dest_t *dests;
} my_user_data_t;
int my_dest_cb(my_user_data_t *user_data, unsigned flags, cups_dest_t *dest) {
if (flags & CUPS_DEST_FLAGS_REMOVED) {
user_data->num_dests = cupsRemoveDest(dest->name, dest->instance, user_data->num_dests, &(user_data->dests));
} else {
user_data->num_dests = cupsCopyDest(dest, user_data->num_dests, &(user_data->dests));
}
return 1;
}
int my_get_dests(cups_ptype_t type, cups_ptype_t mask, cups_dest_t **dests) {
my_user_data_t user_data = { 0, NULL };
if (!cupsEnumDests(CUPS_DEST_FLAGS_NONE, 1000, NULL, type, mask, (cups_dest_cb_t)my_dest_cb, &user_data)) {
cupsFreeDests(user_data.num_dests, user_data.dests);
*dests = NULL;
return 0;
} else {
*dests = user_data.dests;
return user_data.num_dests;
}
}
int main(int argc, const char * argv[]) {
cups_dest_t *dests = NULL;
int num_dests = my_get_dests(0, 0, &dests);
printf("Destination found: %d\n", num_dests);
cups_dest_t *dest;
int i;
const char *value;
for (i = num_dests, dest = dests; i > 0; i--, dest++) {
if (dest->instance == NULL) {
value = cupsGetOption("printer-info", dest->num_options, dest->options);
printf("%s (%s)\n", dest->name, value ? value : "No description");
}
}
return 0;
}
Here is the same thing but in Swift
let destinationsCallback: cups_dest_cb_t = { user_data, flags, dest in
// (void *user_data, unsigned flags, cups_dest_t *dest)
var userDataPointer = user_data!.assumingMemoryBound(to: my_user_data_t.self).pointee
var destData = dest!.pointee
if destData.instance != nil {
print("\(String(cString: destData.name))/\(String(cString: destData.instance))")
} else {
print(String(cString: destData.name))
}
if flags == CUPS_DEST_FLAGS_REMOVED {
userDataPointer.num_dests = cupsRemoveDest(destData.name, destData.instance, userDataPointer.num_dests, &(userDataPointer.dests))
} else {
userDataPointer.num_dests = cupsCopyDest(dest, userDataPointer.num_dests, &(userDataPointer.dests))
}
return 1
}
func getDestinations(type: UInt32, mask: UInt32, dests: UnsafeMutablePointer<cups_dest_t>) -> Int32 {
var userData = my_user_data_t(num_dests: 0, dests: nil)
if cupsEnumDests(UInt32(CUPS_DEST_FLAGS_NONE), 1000, nil, type, mask, destinationsCallback, &userData) != 1 {
return 0
} else {
return userData.num_dests
}
}
I am not able to get the userData to return the correct value which I am assuming is due to the way I handle the pointers.
Greatly appreciate if I am able to get some advice.
IMHO the best way to work with such C libraries in Swift is to work with them in Objective-C. Nevertheless, the main issue seems to be that you are not writing back changes to userData, that's why you always get your initial value. You need to update it in your callback like this
let userDataPointer = user_data!.assumingMemoryBound(to: my_user_data_t.self)
var userData = userDataPointer.pointee
...
// make some changes to userData
userDataPointer.pointee = userData
return 1
Also there seems to be some differences between your C code and the Swift one, like checking flags with 'flags == CUPS_DEST_FLAGS_REMOVED' which, in general, is incorrect way to check flags, and comparing result of cupsEnumDests with 1 when in the original code you check that result is not 0.

C++ overloading operator, compiler doesn't see the operator

CMagazin.h
class CMagazin
{
char *m_nume;
list<CProdus*>List_produse;
public:
void printExpirabile( const char* data);
~CMagazin();
};
CMagazin.cpp
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
**if (p > xdata)**->this problem
}
}
}
CAliment.h
class CAliment :
public CProdus
{
char *m_expirare;
public:
bool operator >(const char*date);
~CAliment();
};
CAliment.cpp
bool CAliment::operator>(const char * date)
{
if (atoi(this->m_expirare) < atoi(date))
{
return 1;
}
else
{
return 0;
}
}
its about ">" operator.in CMagazin.cpp dont use my operator...i need help.
what can i do?I need ">" in CMagazin class. class CAliment its a class derived from CProdus.
Answer is: in Class CProdus the operator must be declared virtual, and in
CMagazin.cpp
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
if (p->operator>( xdata))-> make this!
{
p->print();
}
}
}
}
CProdus*p - is a pointer , need to have object for use this operator -> Try (*p)>xdata
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
if ((*p)>( xdata))-> make this!
{
p->print();
}
}
}
}

Extract issuer (CN) from SSL Certificate using openssl in iOS

I want to extract Issuer CN (Common name) from SSL certificate using openSSL in iOS. I am using the link http://pastebin.com/Vn797Sc0 for extracting the information from the certificate. I am getting the issuer name but could not extract Issuer Common name(Common name) in iOS. Thanks in advance
You can extract the Common Name like the Organization field in the code you linked (Not tested)
static NSString * CertificateGetIssuerCommonName(X509 *certificateX509) {
NSString *issuerCN = nil;
if (certificateX509 != NULL) {
X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
if (issuerX509Name != NULL) {
int nid = OBJ_txt2nid("CN");
int index = X509_NAME_get_index_by_NID(issuerX509Name, nid, -1);
if (index != -1) {
X509_NAME_ENTRY *issuerNameCommonName = X509_NAME_get_entry(issuerX509Name, index);
if (issuerNameEntry) {
ASN1_STRING *issuerCNASN1 = X509_NAME_ENTRY_get_data(issuerNameEntry);
if (issuerCNASN1 != NULL) {
unsigned char *issuerCName = ASN1_STRING_data(issuerCNASN1);
issuerCN = [NSString stringWithUTF8String:(char *)issuerCName];
}
}
}
}
}
return issuerCN;
}
static NSString * CertificateGetIssuerName(X509 *certificateX509)
{
NSString *issuer = nil;
if (certificateX509 != NULL) {
X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
if (issuerX509Name != NULL) {
//NID_commonName extract the common name of the issuer
int index = X509_NAME_get_index_by_NID(issuerX509Name, NID_commonName, -1);
X509_NAME_ENTRY *issuerNameEntry = X509_NAME_get_entry(issuerX509Name, index);
if (issuerNameEntry) {
ASN1_STRING *issuerNameASN1 = X509_NAME_ENTRY_get_data(issuerNameEntry);
if (issuerNameASN1 != NULL) {
unsigned char *issuerName = ASN1_STRING_data(issuerNameASN1);
issuer = [NSString stringWithUTF8String:(char *)issuerName];
}
}
}
}
return issuer;
}

How can I customize a unordered_map so that it uses a custom hash function and a custom equality function?

How can I write my own hash and equity operator for an unordered map so that I can use a char * instead of a std::string as a key?
class PtrStr
{
protected:
const char *m_pcStr;
const int m_nSize;
public:
PtrStr(const char *pcStr, int nSize) : m_pcStr(pcStr), m_nSize(nSize) {}
~PtrStr() {};
const char *GetStr() const { return m_pcStr; }
const int GetSize() const { return m_nSize; }
};
namespace std
{
namespace tr1
{
template<> struct hash<PtrStr>
{
std::size_t operator()(PtrStr const &key) const
{
return MyHashMethod(key);
}
};
}
template<> struct equal_to<PtrStr>
{
bool operator()(const PtrStr &keyA, const PtrStr &keyB) const
{
return (strcmp(const_cast<PtrStr &>(keyA).GetStr(), const_cast<PtrStr &>(keyB).GetStr()) == 0);
return (strcmp(keyA.GetStr(), keyB.GetStr()) == 0);
}
};
}
typedef std::tr1::unordered_map<PtrStr, int> unorderedCharMap;
typedef std::tr1::unordered_map<PtrStr, int>::iterator unorderedCharMapItr;